JavaWeb学习——原理篇学习

2024-08-30 06:04
文章标签 java 学习 web 原理篇

本文主要是介绍JavaWeb学习——原理篇学习,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

一、SpringBoot配置优先级

        首先我们先知道三种SpringBoot支持的配置文件:

        而当在一个Spring项目中,如果同时存在这三个配置文件,那么执行的优先级顺序应是:

properties > yml > yaml 。

补充:属性配置

        另外我们可以通过打包已有的SpringBoot项目,获得jar文件,在文件夹里用cmd指令来进行驱动,而执行启动时,我们就可以进行属性配置。

        了解了文件配置和属性配置后,可以发现它们的执行结果中都可以指定修改本地的port,所以在这说明当都存在时,执行的优先级:

命令行参数(--XXX=XXX)> java系统属性(-Dxxx=xxx)> properties > yml > yaml

二、Bean管理

1、Bean的获取

代码示例(获取DeptController的Bean对象)

package com.itheima.controller;import com.itheima.pojo.Dept;
import com.itheima.pojo.Result;
import com.itheima.service.DeptService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.context.annotation.Scope;
import org.springframework.web.bind.annotation.*;
import java.util.List;//@Lazy
@Scope("prototype")
@RestController
@RequestMapping("/depts")
public class DeptController {@Autowiredprivate DeptService deptService;public DeptController(){System.out.println("DeptController constructor ....");}@GetMappingpublic Result list(){List<Dept> deptList = deptService.list();return Result.success(deptList);}@DeleteMapping("/{id}")public Result delete(@PathVariable Integer id)  {deptService.delete(id);return Result.success();}@PostMappingpublic Result save(@RequestBody Dept dept){deptService.save(dept);return Result.success();}
}package com.itheima;import com.itheima.controller.DeptController;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.context.ApplicationContext;@SpringBootTest
class SpringbootWebConfig2ApplicationTests {@Autowiredprivate ApplicationContext applicationContext; //IOC容器对象//获取bean对象@Testpublic void testGetBean(){//根据bean的名称获取DeptController bean1 = (DeptController) applicationContext.getBean("deptController");System.out.println(bean1);//根据bean的类型获取DeptController bean2 = applicationContext.getBean(DeptController.class);System.out.println(bean2);//根据bean的名称 及 类型获取DeptController bean3 = applicationContext.getBean("deptController", DeptController.class);System.out.println(bean3);}
}

注意

由此我们接下来讲到的就是Bean对象的作用域。

2、Bean作用域

首先了解Spring支持的五种作用域:

延迟Bean对象初始化(@Lazy)学习

        在Spring框架中,@Lazy注解可以用于控制bean的加载时机。默认情况下,当Spring的应用上下文在启动时会创建并初始化所有的单例bean。如果你的应用中有一些bean的创建和初始化过程非常耗费资源,但这些bean在启动阶段可能并不需要使用,或者只在某些特定情况下才需要,那么就可以使用@Lazy注解标记这些bean,让它们在实际被使用时再去创建和初始化。

        具体来说,@Lazy标记的bean在以下三种情况下会被实例化和初始化:

  1. 当应用上下文中获取到这个bean的引用时,例如通过ApplicationContext.getBean()调用,或者在其他bean中通过依赖注入获取这个bean。

  2. 当这个bean被用作其他bean的依赖,并且这个依赖的bean被实例化时。注意,如果依赖的bean也是懒加载的,那么原始bean仍然不会在这时被加载。

  3. 当这个bean是一个@Scheduled任务,当任务调度开始时,这个bean会被初始化。

        注意,在Spring Boot中,主程序类(带有@SpringBootApplication注解的类)不能标记为@Lazy,否则会导致应用上下文初始化失败。此外,@Lazy注解对@Configuration类也是有效的,如果一个@Configuration类被标记为@Lazy,那么该配置类中所有的@Bean方法都会被延迟加载。

代码示例

package com.itheima.controller;import com.itheima.pojo.Dept;
import com.itheima.pojo.Result;
import com.itheima.service.DeptService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.context.annotation.Scope;
import org.springframework.web.bind.annotation.*;
import java.util.List;@Lazy //延迟Bean初始化
@Scope("prototype")
@RestController
@RequestMapping("/depts")
public class DeptController {@Autowiredprivate DeptService deptService;public DeptController(){System.out.println("DeptController constructor ....");}@GetMappingpublic Result list(){List<Dept> deptList = deptService.list();return Result.success(deptList);}@DeleteMapping("/{id}")public Result delete(@PathVariable Integer id)  {deptService.delete(id);return Result.success();}@PostMappingpublic Result save(@RequestBody Dept dept){deptService.save(dept);return Result.success();}
}

@Scope学习

@Scope 是Spring Framework的一个关键注解,用于指定Spring管理的bean的范围或生命周期。Spring支持以下几种bean的作用域:

singleton:这是默认的作用域,对于每个Spring IoC容器,只会存在一个bean的实例。

@Scope("singleton")
@Component
public class SingletonBean {
}

prototype:对于每一次请求,都会创建一个新的bean实例。

@Scope("prototype")
@Component
public class PrototypeBean {
}

request:该作用域仅在web应用中有效,每次HTTP请求都会创建一个新的bean实例。

@Scope("request")
@Component
public class RequestBean {
}

session:该作用域仅在web应用中有效,同一个HTTP Session共享一个bean实例。

@Scope("session")
@Component
public class SessionBean {
}

 application:在整个web应用中,只有一个共享的bean实例。

@Scope("application")
@Component
public class ApplicationBean {
}

websocket:在同一个websocket会话中,有一个共享的bean实例。

@Scope("websocket")
@Component
public class WebSocketBean {
}

        除了以上这些预定义的作用域,Spring也允许你自定义作用域。

        要注意,singleton 和 prototype 作用域在任何类型的Spring应用中都可以使用,其他作用域需要在web环境中才能有效。

        补充

3、第三方Bean

启动类代码示例

package com.itheima;import org.dom4j.io.SAXReader;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Bean;@SpringBootApplication
public class SpringbootWebConfig2Application {public static void main(String[] args) {SpringApplication.run(SpringbootWebConfig2Application.class, args);}//声明第三方bean@Bean //将当前方法的返回值对象交给IOC容器管理, 成为IOC容器beanpublic SAXReader saxReader(){return new SAXReader();}
}package com.itheima;import com.itheima.controller.DeptController;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.context.ApplicationContext;@SpringBootTest
class SpringbootWebConfig2ApplicationTests {
@Autowiredprivate SAXReader saxReader;//第三方bean的管理@Testpublic void testThirdBean() throws Exception {SAXReader saxReader = new SAXReader();Document document = saxReader.read(this.getClass().getClassLoader().getResource("1.xml"));Element rootElement = document.getRootElement();String name = rootElement.element("name").getText();String age = rootElement.element("age").getText();System.out.println(name + " : " + age);}
}

 config单独创包使用代码示例(此时不使用启动类的代码)

package com.itheima.config;import com.itheima.service.DeptService;
import org.dom4j.io.SAXReader;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;@Configuration //配置类
public class CommonConfig {//声明第三方bean@Bean //将当前方法的返回值对象交给IOC容器管理, 成为IOC容器bean//通过@Bean注解的name/value属性指定bean名称, 如果未指定, 默认是方法名public SAXReader reader(DeptService deptService){System.out.println(deptService);return new SAXReader();}}package com.itheima;import com.itheima.controller.DeptController;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.context.ApplicationContext;@SpringBootTest
class SpringbootWebConfig2ApplicationTests {
@Autowiredprivate SAXReader saxReader;//第三方bean的管理@Testpublic void testThirdBean() throws Exception {//SAXReader saxReader = new SAXReader();Document document = saxReader.read(this.getClass().getClassLoader().getResource("1.xml"));Element rootElement = document.getRootElement();String name = rootElement.element("name").getText();String age = rootElement.element("age").getText();System.out.println(name + " : " + age);}@Testpublic void testGetBean2(){Object saxReader = applicationContext.getBean("reader");System.out.println(saxReader);}
}

 三、SpringBoot原理

1、起步依赖

        在Spring Boot中,起步依赖(Starters)是一种特殊的模块,它包含了一组相关的依赖,这些依赖可以一起提供一些功能。这种机制允许你通过添加一个起步依赖,就可以拥有一组相关的依赖,简化了项目的依赖设定。

        这是Spring Boot的一种约定优于配置的思想,通过预设一些默认配置来简化项目设置。例如,如果你想在项目中使用Spring MVC,只需要在项目中添加“spring-boot-starter-web”这个起步依赖,你就会获得包括Spring MVC,Tomcat,Spring Boot等在内的一系列相关的依赖。

        请注意,起步依赖的高度依赖于Spring Boot的自动配置功能,只有在Spring Boot的自动配置激活的情况下,起步依赖才能发挥作用。此外,虽然Spring Boot包含了很多预先定义好的起步依赖,但是你仍然可以自定义自己的起步依赖。

2、自动配置

概念叙述

        Spring Boot 的自动配置是其核心特性之一,它可以根据项目中的类路径、其他Spring beans或各种属性设置自动配置Spring应用。自动配置旨在提供合理的默认值,以便在可能的情况下,Spring Boot应用无需任何配置即可运行。

        自动配置是通过@EnableAutoConfiguration注解实现的,这个注解通常在主类或者主配置类上添加。

        例如,如果你的 classpath 下有 spring-webmvc,那么 Spring Boot 自动配置会判断你正在开发一个web应用,并初始化相应的Spring MVC配置,例如配置 DispatcherServlet

        自动配置通过尝试配置你可能需要的bean来工作。例如,如果 mysql-connector-java 在classpath中,而你没有配置任何数据库连接,那么 Spring Boot 会默认自动配置一个内存数据库(如 H2,HSQL或 Derby)。

        虽然自动配置提供了合理的默认行为,你仍然可以通过在应用程序的 application.properties 或 application.yml 文件中指定属性,或者通过自定义的Configuration类来修改默认行为。如果你定义了自己的配置,则自动配置就会步入后台。

        你可以使用 @SpringBootApplication 注解来启用自动配置,这个注解实际上是 @Configuration@EnableAutoConfiguration 和 @ComponentScan 的组合。

@SpringBootApplication
public class Application {

    public static void main(String[] args) {
        SpringApplication.run(Application.class, args);
    }
}

         通过运行 mvn spring-boot:run 或运行上述 main 方法,Spring Boot 应用将会启动并执行所有的自动配置逻辑。

原理认识

        Spring Boot 自动配置的核心工作原理是根据类路径中的类和已有的 Bean 定义以及各类属性参数来自动创建和注册 Bean 定义。

        以下是其工作原理的详细步骤:

        1. `@SpringBootApplication`注解将启动自动配置,因为它包含了`@EnableAutoConfiguration`注解。如果你查看`@EnableAutoConfiguration`的注解定义,你可以看见它的一个关键元注解是`@Import(AutoConfigurationImportSelector.class)`。是这个`AutoConfigurationImportSelector`类起了关键作用。

        2. 当Spring Boot启动时,`AutoConfigurationImportSelector`类会自动加载 `META-INF/spring.factories` 文件中配置的所有 `EnableAutoConfiguration` 的实现类。

        3. `spring.factories` 文件是一个内置文件,包含了大量的自动配置类的全路径。这些自动配置类都是在特定条件下会生效的配置类,比如对应的库在类路径中,或者对应的Bean尚未定义,等等。

        4. `AutoConfigurationImportSelector` 将所有从 `spring.factories` 文件读取到的自动配置类汇总为一个 `List`,然后添加到 IoC 容器中。

        5. 每一个自动配置类通常都有 `@Configuration` 和 `@Conditional` 等注解,其中 `@Configuration` 表明这是一个配置类,而 `@Conditional` 确保了只有在满足某些条件时,相应的配置才会生效。例如,当类路径下存在某个特定的类时,或者Spring环境中存在某个特定的Bean时,等等。

        6. 若条件判断成功,自动配置类中的配置(比如定义某个Bean)就会生效,自动配置在这一刻真正发挥了作用。

        这就是 Spring Boot 自动配置的基本原理。需要注意的是,Spring Boot会尽量晚地自动配置,即它会先读取用户自定义的配置,再考虑自动配置,也就是说,用户的自定义配置优先级更高。

        :在学习自动配置原理这一知识点是在黑马视频上看的,视频中出现了导入类实现Bean对象的代码和方法,在这不好叙说,推荐后面有所疑惑或遗忘可以去回顾。

源码追踪

@Conditional学习

  @Conditional 是 Spring 4 引入的一个核心注解,它用于表示只有特定条件成立时,才使得带有这个注解的类、方法、Bean 等得以完全生效或部分生效。它可以用于 @Configuration@Component@Bean 注解等。

下面是一个@Conditional使用的注释示例图(仅使用说明三种)

@ConditionalOnClass使用方式

        @ConditionalOnClass 是 Spring Boot 提供的一个条件注解,表示当类路径(Classpath)下存在指定的类时,当前注解修饰的代码才会生效。这个注解通常用在自动配置类中,用于检测某个特定的类是否存在。

这是一个简单的示例:

@Configuration
@ConditionalOnClass(ExampleService.class)
public class ExampleAutoConfiguration {@Beanpublic ExampleService exampleService() {return new ExampleService();}}

        在上述代码中,ExampleAutoConfiguration 会被 Spring 加载为配置类,但是其中定义的 exampleService Bean 只有在 ExampleService 类存在于类路径下时才会被创建。

        如果 ExampleService 类不存在于类路径下,那么 exampleService() 方法(也就是创建 exampleService 的 Bean 定义)将不会执行,也就是说,exampleService Bean 不会被创建和注册。

        使用 @ConditionalOnClass 可以避免在类路径下不存在某个类时导致的自动配置失败。这在创建可以自动适应对应库是否可用的自动配置类时非常有用。

        当我们使用 @ConditionalOnClass 注解时,除了可以通过传递 Class 对象外,也可以通过名称(name)指定类名。使用名称指定是一种更为安全的方式,因为这样不需要直接依赖该类。即使类路径下没有该类,也不会报 NoClassDefFoundError

        下面是一个使用 name 参数的例子:

@Configuration
@ConditionalOnClass(name = "com.example.ExampleService")
public class ExampleAutoConfiguration {//...}

        在上述代码中,只有当类路径下存在 com.example.ExampleService 这个类时,带有@ConditionalOnClass 注解的 ExampleAutoConfiguration 配置类才会生效。

        所以,当你确定类路径下一定存在某个类时,可以直接传 Class;当你不确定类路径下是否存在某个类,或者你不想增加对此类的直接依赖时,可以通过 name 指定类名。

@ConditionalOnMissingBean学习

  @ConditionalOnMissingBean 是 Spring Boot 提供的另外一个条件注解,它表示当容器中不存在指定 Bean 时,当前注解修饰的代码才会生效。这主要应用于自动配置场景,使得只有用户没有自定义相应的 Bean 时,才会自动配置。

        下面是一个简单的示例:

@Configuration
public class ExampleAutoConfiguration {@Bean@ConditionalOnMissingBeanpublic ExampleService exampleService() {return new ExampleService();}}

        在这段代码中,exampleService 的 Bean 定义(也就是 exampleService() 方法)只有在容器中还没有叫做 exampleService 的 Bean 时才会生效。也就是说,如果用户已经创建了自己的 exampleService Bean,那么 Spring Boot 就不会再自动配置。

   @ConditionalOnMissingBean 还可以指定 Bean 的类型。比如:

@Bean
@ConditionalOnMissingBean(ExampleService.class)
public ExampleService exampleService() {return new ExampleService();
}

        在这个例子中,只有当容器中没有任何类型为 ExampleService 的 Bean 存在时,这个自动配置的 Bean 才会生效。

@ConditionalOnProperty学习

  @ConditionalOnProperty 是 Spring Boot 提供的一种条件注解,它表示当指定的配置属性满足特定的条件,被这个注解修饰的代码才会生效。

        注解 @ConditionalOnProperty 主要有两个属性需要设置:

  • name:(必须)配置属性的名称,比如 spring.datasource.driverClassName
  • havingValue:(可选)配置属性的值,只有当属性存在,并且与 havingValue 的值相同,条件才成立。如果不设置此属性,那么只要定义了这个属性,条件就成立。

        还有一个重要的 matchIfMissing 属性,默认为 false,表示如果没有设置这个属性,就按照不匹配处理。如果设置为 true,那么在属性不存在的情况下也认为匹配。

        下面是一个示例,在这个例子中,只有当配置文件中设置了 example.feature.enabled=trueexampleFeature Bean 才会被创建:

@Configuration
public class ExampleAutoConfiguration {@Bean@ConditionalOnProperty(name = "example.feature.enabled", havingValue = "true")public ExampleFeature exampleFeature() {return new ExampleFeature();}}

        如果我们希望在没有明确设置 example.feature.enabled 的情况下也创建 exampleFeature Bean(也就是默认为开启状态),可以修改之前的代码如下:

@Bean
@ConditionalOnProperty(name = "example.feature.enabled", matchIfMissing = true)
public ExampleFeature exampleFeature() {return new ExampleFeature();
}

        在这个例子里,如果配置中没有 example.feature.enabled 这个属性,exampleFeature Bean 依然会被创建。

3、自定义starter实现

        黑马视频里有学习进行自定义starter的案例,在这不好讲解,本人电脑里有跟随做的代码,以后如果回顾时有疑惑之处,可以进行分析,如果是别人再看的话,建议去原视频处看看并跟随写代码。

这篇关于JavaWeb学习——原理篇学习的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/1119987

相关文章

Spring boot整合dubbo+zookeeper的详细过程

《Springboot整合dubbo+zookeeper的详细过程》本文讲解SpringBoot整合Dubbo与Zookeeper实现API、Provider、Consumer模式,包含依赖配置、... 目录Spring boot整合dubbo+zookeeper1.创建父工程2.父工程引入依赖3.创建ap

SpringBoot结合Docker进行容器化处理指南

《SpringBoot结合Docker进行容器化处理指南》在当今快速发展的软件工程领域,SpringBoot和Docker已经成为现代Java开发者的必备工具,本文将深入讲解如何将一个SpringBo... 目录前言一、为什么选择 Spring Bootjavascript + docker1. 快速部署与

Spring Boot spring-boot-maven-plugin 参数配置详解(最新推荐)

《SpringBootspring-boot-maven-plugin参数配置详解(最新推荐)》文章介绍了SpringBootMaven插件的5个核心目标(repackage、run、start... 目录一 spring-boot-maven-plugin 插件的5个Goals二 应用场景1 重新打包应用

SpringBoot+EasyExcel实现自定义复杂样式导入导出

《SpringBoot+EasyExcel实现自定义复杂样式导入导出》这篇文章主要为大家详细介绍了SpringBoot如何结果EasyExcel实现自定义复杂样式导入导出功能,文中的示例代码讲解详细,... 目录安装处理自定义导出复杂场景1、列不固定,动态列2、动态下拉3、自定义锁定行/列,添加密码4、合并

Spring Boot集成Druid实现数据源管理与监控的详细步骤

《SpringBoot集成Druid实现数据源管理与监控的详细步骤》本文介绍如何在SpringBoot项目中集成Druid数据库连接池,包括环境搭建、Maven依赖配置、SpringBoot配置文件... 目录1. 引言1.1 环境准备1.2 Druid介绍2. 配置Druid连接池3. 查看Druid监控

Java中读取YAML文件配置信息常见问题及解决方法

《Java中读取YAML文件配置信息常见问题及解决方法》:本文主要介绍Java中读取YAML文件配置信息常见问题及解决方法,本文给大家介绍的非常详细,对大家的学习或工作具有一定的参考借鉴价值,需要... 目录1 使用Spring Boot的@ConfigurationProperties2. 使用@Valu

创建Java keystore文件的完整指南及详细步骤

《创建Javakeystore文件的完整指南及详细步骤》本文详解Java中keystore的创建与配置,涵盖私钥管理、自签名与CA证书生成、SSL/TLS应用,强调安全存储及验证机制,确保通信加密和... 目录1. 秘密键(私钥)的理解与管理私钥的定义与重要性私钥的管理策略私钥的生成与存储2. 证书的创建与

浅析Spring如何控制Bean的加载顺序

《浅析Spring如何控制Bean的加载顺序》在大多数情况下,我们不需要手动控制Bean的加载顺序,因为Spring的IoC容器足够智能,但在某些特殊场景下,这种隐式的依赖关系可能不存在,下面我们就来... 目录核心原则:依赖驱动加载手动控制 Bean 加载顺序的方法方法 1:使用@DependsOn(最直

SpringBoot中如何使用Assert进行断言校验

《SpringBoot中如何使用Assert进行断言校验》Java提供了内置的assert机制,而Spring框架也提供了更强大的Assert工具类来帮助开发者进行参数校验和状态检查,下... 目录前言一、Java 原生assert简介1.1 使用方式1.2 示例代码1.3 优缺点分析二、Spring Fr

java使用protobuf-maven-plugin的插件编译proto文件详解

《java使用protobuf-maven-plugin的插件编译proto文件详解》:本文主要介绍java使用protobuf-maven-plugin的插件编译proto文件,具有很好的参考价... 目录protobuf文件作为数据传输和存储的协议主要介绍在Java使用maven编译proto文件的插件