[023-03].第3节:自动配置原理

我的后端学习大纲

SpringBoot学习大纲


1.SpringBoot特点

1.1.SpringBoot的依赖管理:

a.父项目做依赖管理:

依赖管理    
<parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.3.4.RELEASE</version>
</parent>

他的父项目
 <parent>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-dependencies</artifactId>
    <version>2.3.4.RELEASE</version>
  </parent>

spring-boot-starter-parent 还有个父项目,父项目做依赖管理,在父项目中几乎声明了所有开发中常用的依赖的版本号,自动版本仲裁机制

几乎声明了所有开发中常用的依赖的版本号,自动版本仲裁机制,即如果程序员没有指定某个依赖 jar 的版本,则以父项目指定的版本为准

b.开发导入starter场景启动器

  • 1.见到很多 spring-boot-starter-* : * 就是某种场景
  • 2.只要引入starter,这个场景的所有常规需要的依赖我们都自动引入,比如我们做 web 开发引入了,该 starter 将导入与 web 开发相关的所有包
    在这里插入图片描述
    • 2.1.依赖树 : 可以看到 spring-boot-starter-web场景依赖帮我们引入了 spring-webmvc,spring-web开发模块,还引入了 spring-boot-starter-tomcat 场景,spring-boot-starter-json 场景,这些场景下面又引入了一大堆相关的包,这些依赖项可以快速启动和运行一个项目,提高开发效率
    • 2.2.所有场景启动器最基本的依赖就是 spring-boot-starter , 在依赖树分析可以看到,这个依赖也就是 SpringBoot 自动配置的核心依赖
      在这里插入图片描述
  • 3.官方提供的 starter
  • 4.SpringBoot所有支持的场景(场景启动器介绍)都在这个文档中可以找到;所以在开发的时候,要用什么功能的场景,就导入什么场景的启动器
  • 5.SpringBoot 也支持第三方 starter, *-spring-boot-starter: 这种的是第三方为我们提供的简化开发的场景启动器
    • 第三方 starter 不要从 spring-boot 开始,因为这是官方 spring-boot 保留的命名方式的。
    • 第三方启动程序通常以项目名称开头。例如,名为 thirdpartyproject 的第三方启动程序项目通常被命名为 thirdpartyproject-spring-boot-starter
      在这里插入图片描述
      在这里插入图片描述
  • 6.所有场景启动器最底层最基本的的依赖都是:spring-boot-starter,这个就是springboot自动配置的核心依赖
<dependency>
	<groupId>org.springframework.boot</groupId>
	<artifactId>spring-boot-starter</artifactId>
	<version>2.3.4.RELEASE</version>
	<scope>compile</scope>
</dependency>

c.spring-boot-starter-parent:依赖的仲裁中心

  • 1.父项目做依赖管理,当子项目只要继承了父项目,那么就会使用相同的依赖版本,不用自己再定义依赖的版本了;如下定义了第一层父项目:
    在这里插入图片描述
  • 2.这个父项目是进行:依赖管理的,在这个父项目的上面还有父项目,点击去可以看到如下图所示:
//第二层父项目
<parent>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-dependencies</artifactId>
    <version>2.5.2</version>
  </parent>

在这里插入图片描述

  • 3.在这个父项目中,点dependencies,进去之后,如下图所示;可以看到定义了很多jar包的依赖版本
    在这里插入图片描述
  • 4.由上可见,依赖管理中,几乎声明了所有开发中常用的依赖的版本号,自动版本仲裁机制,继承parent模块,可以避免相同技术使用不同版本的依赖,避免了依赖版本冲突;
  • 5.继承parent依赖的形式我们也可以直接采用引入依赖的形式来实现效果:
    在这里插入图片描述

d.依赖的版本号更改:

有时候,我们需要更改依赖的版本时候,我们需要在pom.xml这个配置文件中更改,比如下面这个例子:


1.2.自动配置:

a.在SSM中的配置与SpringBoot自动配置的开发说明:

  • 1.在SSM 整合时,需要配置 Tomcat 、配置 SpringMVC、配置如何扫描包、配置字符过滤器、配置视图解析器、文件上传等,如下图所示的配置,非常麻烦。而在SpringBoot 中,存在自动配置机制,提高开发效率
    在这里插入图片描述
    在这里插入图片描述

b.引入spring-boot-starter-web来分析自动配置:

b1.自动配置概述:
  • 1引入这个场景依赖后,就会帮我们导入了web模块正常运行所依赖的组件;
    在这里插入图片描述
  • 2.Spring Boot将所有的功能场景都抽取出来,做成一个个的starters(启动器),只需要在项目里面引入这些starter相关场景的所有依赖都会自动导入进来。
    在这里插入图片描述
b2.查看依赖引入后的所有组件:
  • 1.SpringApplication.run(MainApplication.class,args)返回IOC容器,在这个容器中包含了在容器中的所有组件
    在这里插入图片描述
    在这里插入图片描述
b3.引入web依赖后SpringBoot 自动配置了哪些?

1.自动引入Tomcat依赖,配置 了Tomcat
在这里插入图片描述
2.自动配置 SpringMVC:

  • 引入SpringMVC全套组件
  • 自动配好SpringMVC常用组件(功能)
    在这里插入图片描述

3.自动配置 Web 常用功能:

  • 1.如字符过滤器,解决了字符编码问题,不会出现中文乱码的情况
    在这里插入图片描述

4.默认的包结构 :

  • 1.主程序所在包及其下面的所有子包里面的组件都会被默认扫描进来 ,不再需要配置之前的包扫描配置
    在这里插入图片描述
  • 2.@SpringBootApplication注解说明: @SpringBootApplication = @SpringBootConfiguration + @EnableAutoConfiguration + @ComponentScan()
    在这里插入图片描述
  • 3.修改默认扫描包结构:修改变包扫描路径,@SpringBootApplication(scanBasePackages="com.jianqun")
@SpringBootApplication
这个注解等同于
@SpringBootConfiguration
@EnableAutoConfiguration
@ComponentScan("com.jianqun")

在这里插入图片描述

  • 4.如果有多个包,就可以写成数组的形式,如@SpringBootApplication(scanBasePackages = {"com.jianqun",“xx.cc.ddd”)}或者也可以使用@ComponentScan ()指定扫描路径

5.各种配置拥有默认值:

  • 1.默认配置最终都是映射到某个类上:如:MultipartProperties
    在这里插入图片描述
  • 2.配置文件的值最终会绑定每个类上,这个类会在容器中创建对象
    在这里插入图片描述
    在这里插入图片描述

6.按需加载所有自动配置项

  • 1.springboot中有非常多的starter,引入了哪些场景,哪些个场景的自动配置才会开启
  • 2.SpringBoot中所有的自动配置功能都在spring-boot-autoconfigure 包里面
  • 3.在 SpringBoot 的自动配置包 , 一般是 XxxAutoConfiguration.java, 对应XxxxProperties.java, 如图
    在这里插入图片描述

2.容器功能:

2.1.Spring实现组件添加

在这里插入图片描述

  //@Configuration告诉SpringBoot这是一个配置类 == 配置文件
@Configuration(proxyBeanMethods = false)
public class MyConfig {
    @Bean 
    public User user01(){
        return new User ("zhangsant","18");;
    }

    @Bean("tom")//给组件命名
    public Pet tomcatPet(){
        return new Pet("tomcat");
    }
}

2.2.SpringBoot中实现注入组件

a. @Configuration注解实现注入组件:

a1.实现方式:
  • 1.在类上添加注解@Configuration等同于告诉SpringBoot这是一个配置类:
    在这里插入图片描述
a2.对配置类说明:
a2-1.配置类里面使用@Bean标注在方法上给容器注册组件默认也是单实例的
@SpringBootConfiguration
@EnableAutoConfiguration
@ComponentScan("com.atguigu.boot")
public class MainApplication {

    public static void main(String[] args) {
        //1、返回我们IOC容器
        ConfigurableApplicationContext run = SpringApplication.run(MainApplication.class, args);

        //2、查看容器里面的组件
        String[] names = run.getBeanDefinitionNames();
        for (String name : names) {
            System.out.println(name);
        }

        //3、从容器中获取组件
        Pet tom01 = run.getBean("tom", Pet.class);
        Pet tom02 = run.getBean("tom", Pet.class);
        System.out.println("组件:"+(tom01 == tom02));
    }
}
a2-2.配置类本身也是容器中的一个组件
@SpringBootConfiguration
@EnableAutoConfiguration
@ComponentScan("com.atguigu.boot")
public class MainApplication {
    public static void main(String[] args) {
        //com.atguigu.boot.config.MyConfig$$EnhancerBySpringCGLIB$$51f1e1ca@1654a892
        MyConfig bean = run.getBean(MyConfig.class);
        System.out.println(bean);
    }
}
a2-3.proxyBeanMethods:代理bean的方法:

1.两种模式说明:

  • Full模式 == (proxyBeanMethods = true)【保证每个@Bean方法被调用多少次返回的组件都是单实例的
  • Lite模式 == (proxyBeanMethods = false)【每个@Bean方法被调用多少次返回的组件都是新创建的】

2.组件依赖必须使用Full模式默认。其他默认是否Lite模式

  • 配置 类组件之间无依赖关系用Lite模式加速容器启动过程,减少判断
  • 配置类组件之间有依赖关系,方法会被调用得到之前单实例组件,用Full模式

3.编码说明两种模式:

  • 1.定义实体类:
    在这里插入图片描述
  • 2.编写配置类:
//告诉SpringBoot这是一个配置类 == 配置文件
@Configuration(proxyBeanMethods = true) 
public class MyConfig {
    /**
     * Full:外部无论对配置类中的这个组件注册方法调用多少次获取的都是之前注册容器中的单实例对象
     * @return
     */
    @Bean //给容器中添加组件。以方法名作为组件的id。返回类型就是组件类型。返回的值,就是组件在容器中的实例
    public User user01(){
        User zhangsan = new User("zhangsan", 18);
        //user组件依赖了Pet组件
        zhangsan.setPet(tomcatPet());
        return zhangsan;
    }

    @Bean("tom")
    public Pet tomcatPet(){
        return new Pet("tomcat");
    }
}
  • 3.启动类中测试:
@SpringBootConfiguration
@EnableAutoConfiguration
@ComponentScan("com.atguigu.boot")
public class MainApplication {
    public static void main(String[] args) { 
        //如果@Configuration(proxyBeanMethods = true)代理对象调用方法。SpringBoot总会检查这个组件是否在容器中有。
        //保持组件单实例
        User user = bean.user01();
        User user1 = bean.user01();
        System.out.println(user == user1);
        
        User user01 = run.getBean("user01", User.class);
        Pet tom = run.getBean("tom", Pet.class);

        System.out.println("用户的宠物:"+(user01.getPet() == tom));
    }
}
a3.测试获取新注入的组件:
@SpringBootConfiguration
@EnableAutoConfiguration
@ComponentScan("com.atguigu.boot")
public class MainApplication {

    public static void main(String[] args) {
        //1、返回我们IOC容器
        ConfigurableApplicationContext run = SpringApplication.run(MainApplication.class, args);

        //2、查看容器里面的组件
        String[] names = run.getBeanDefinitionNames();
        for (String name : names) {
            System.out.println(name);
        }

        //3、从容器中获取组件(验证组件是否是单实例的)
        Pet tom01 = run.getBean("tom", Pet.class);
        Pet tom02 = run.getBean("tom", Pet.class);
        System.out.println("组件:"+(tom01 == tom02));

        //4、com.atguigu.boot.config.MyConfig$$EnhancerBySpringCGLIB$$51f1e1ca@1654a892
        MyConfig bean = run.getBean(MyConfig.class);
        System.out.println(bean);

        // 如果@Configuration(proxyBeanMethods = true)代理对象调用方法。
        // SpringBoot总会检查这个组件是否在容器中有。
        // 保持组件单实例
        // 如果@Configuration(proxyBeanMethods = false)就不再是单例的了
        User user = bean.user01();
        User user1 = bean.user01();
        System.out.println(user == user1);
        User user01 = run.getBean("user01", User.class);
        Pet tom = run.getBean("tom", Pet.class);
        System.out.println("用户的宠物:"+(user01.getPet() == tom));
    }
}

b.一些常用注解实现注入组件:

  • 1.@Bean:
  • 2.@Component:
  • 3.@Controller:控制器组件
  • 4.@Service:业务逻辑组件
  • 5.@Repository:数据库层的组件
  • 6.@ComponentScan:包扫描组件

c.注解@Import实现注入组件

  • 1.@Import是导入组件使用的,如导入第三方jar包中指定类名的组件或者导入自定义名称的组件等,它会自动的调用组件的无参构造器来创建对象放在容器中
  • 2.@Import给容器中自动创建出这两个类型的组件、默认组件的名字就是全类名
    在这里插入图片描述
  • 3.@Import 高级用法

d.注解@Conditional:实现注入组件

  • 1.条件装配:满足Conditional指定的条件,则进行组件注入
    在这里插入图片描述
  • 2.测试条件装配:只有当注解中的条件成立的时候,类中的类容才会生效
@Configuration(proxyBeanMethods = false)
//@ConditionalOnBean(name = "tom")
@ConditionalOnMissingBean(name = "tom")
public class MyConfig {
    public User user01(){
        User zhangsan = new User("zhangsan", 18);
        //user组件依赖了Pet组件
        zhangsan.setPet(tomcatPet());
        return zhangsan;
    }

    @Bean("tom22")
    public Pet tomcatPet(){
        return new Pet("tomcat");
    }
}
  • 3.测试方法:
public static void main(String[] args) {
        //1、返回我们IOC容器
        ConfigurableApplicationContext run = SpringApplication.run(MainApplication.class, args);

        //2、查看容器里面的组件
        String[] names = run.getBeanDefinitionNames();
        for (String name : names) {
            System.out.println(name);
        }

        boolean tom = run.containsBean("tom");
        System.out.println("容器中Tom组件:"+tom);

        boolean user01 = run.containsBean("user01");
        System.out.println("容器中user01组件:"+user01);

        boolean tom22 = run.containsBean("tom22");
        System.out.println("容器中tom22组件:"+tom22);
    }

2.3.原生配置文件引入:

a.注解说明:

  • 1.使用这个主键可以把原生配置文件引入,意思就是在老项目中是xml配置文件,如果要都改成注解方式,那么就比较麻烦,所以我们就以成配置引入的方式来进行操作:

b.实现引入原生配置文件:

  • 1.beans.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:context="http://www.springframework.org/schema/context"
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context https://www.springframework.org/schema/context/spring-context.xsd">

    <bean id="haha" class="com.atguigu.boot.bean.User">
        <property name="name" value="zhangsan"></property>
        <property name="age" value="18"></property>
    </bean>

    <bean id="hehe" class="com.atguigu.boot.bean.Pet">
        <property name="name" value="tomcat"></property>
    </bean>
</beans>
  • 2.注解引入原配置文件:
@ImportResource("classpath:beans.xml")
public class MyConfig {}
   boolean haha = run.containsBean("haha");
   boolean hehe = run.containsBean("hehe");
   System.out.println("haha:"+haha);//true
   System.out.println("hehe:"+hehe);//true

2.4.配置绑定:

a.注解@ConfigurationProperties + @Component 实现配置绑定

  • 1.配置文件:
    在这里插入图片描述
  • 2.SpringBoot中实现属性封装到javaBean中:只有在容器中的组件,才会拥有SpringBoot提供的强大功能,所以添加@Component组件,把它加入到容器中 ,这样就可以实现类的属性与配置文件中的字段对应
@Component
@ConfigurationProperties(prefix = "mycar")
public class Car {
    private String brand;
    private Integer price;

    public String getBrand() {
        return brand;
    }

    public void setBrand(String brand) {
        this.brand = brand;
    }

    public Integer getPrice() {
        return price;
    }

    public void setPrice(Integer price) {
        this.price = price;
    }

    @Override
    public String toString() {
        return "Car{" +
                "brand='" + brand + '\'' +
                ", price=" + price +
                '}';
    }
}
  • 3.测试:
    在这里插入图片描述
    在这里插入图片描述

b.注解@EnableConfigurationProperties + @ConfigurationProperties 实现配置绑定

  • 1.更改配置类文件:
    在这里插入图片描述
  • 2.这种方式不再需要@Componemt注解,在开发的时候,我们如果引用的是第三方类且未标记@Component注解,就可以使用这种方式实现配置绑定
    在这里插入图片描述

3.SpringBoot中的自动配置原理:

3.1.引导加载自动配置类

  • 1.从主方法开始分析,先看@SpringBootApplication:@SpringBootApplication = @SpringBootConfiguration + @EnableAutoConfiguration + @ComponentScan
    在这里插入图片描述
    @SpringBootConfiguration
    @EnableAutoConfiguration
    @ComponentScan(excludeFilters = { @Filter(type = FilterType.CUSTOM, classes = TypeExcludeFilter.class),
    		@Filter(type = FilterType.CUSTOM, classes = AutoConfigurationExcludeFilter.class) })
    public @interface SpringBootApplication {
    
    }
    

a.@ComponentScan介绍:

  • 1.@ComponentScan代表的是包扫描

b.@SpringBootConfiguration:

  • 1.@SpringBootConfiguration点击去就是@Configuration:代表当前类是一个配置类
    在这里插入图片描述

c.@EnableAutoConfiguration:

c1.@EnableAutoConfiguration分析:
  • 1.@EnableAutoConfiguration —> ctrl + h 可以得到如下:@EnableAutoConfiguration = @AutoConfigurationPackage + @Import()
    • @AutoConfigurationPackage 就是自动配置包,指定了默认的包规则
    • @import注解就是导入组件
      在这里插入图片描述
      在这里插入图片描述
c2.注解@AutoConfigurationPackage分析:
  • 1.@AutoConfigurationPackage ctrl + h —>可以得到如下代码:发现是利用import注解导入了一个AutoConfigurationPackages.Registrar组件
    在这里插入图片描述
  • 2.AutoConfigurationPackages.Registrar** ctrl + h 再点进去分析—> 由下图可知利用Registrar给容器注入一系列的组件;
    在这里插入图片描述
    在这里插入图片描述
  • 3.由上面代码的:registerBeanDefinitions()方法可知,传递了两个参数;
    • 参数1: AnnotationMetadata metadata:第一个参数传递的是注解的元信息
      • 这里所指的这个注解就是:@AutoConfigurationPackage,代表的就是这个注解标在哪个位置;
      • 在这里这个注解就是标在了MainApplication这个类位置上; 当元信息拿来后,用new PackageImports(metadata).getPackageNames()获取到包名称,然后toArray(new String[0])转封装成数组
      • 最后register(registry, new PackageImports(metadata).getPackageNames().toArray(new String[0]))意思就是把指定 某MainApplication这个包里面的所有组件批量注册到容器中
c3.来分析下注解:@Import(AutoConfigurationImportSelector.class)

在这里插入图片描述

		@Override
		public String[] selectImports(AnnotationMetadata annotationMetadata) {
			if (!isEnabled(annotationMetadata)) {
				return NO_IMPORTS;
			}
			AutoConfigurationEntry autoConfigurationEntry = getAutoConfigurationEntry(annotationMetadata);
			return StringUtils.toStringArray(autoConfigurationEntry.getConfigurations());
		}
	
		@Override
		public Predicate<String> getExclusionFilter() {
			return this::shouldExclude;
		}
	
		private boolean shouldExclude(String configurationClassName) {
			return getConfigurationClassFilter().filter(Collections.singletonList(configurationClassName)).isEmpty();
		}

由上述代码可知:

  • 1.利用:getAutoConfigurationEntry(annotationMetadata)给容器批量导入一些组件
  • 2.调用List<String> configurations = getCandidateConfigurations(annotationMetadata, attributes)获取到所有需要导入到容器中的配置类
  • 3.利用工厂加载 Map<String, List<String>> loadSpringFactories(@Nullable ClassLoader classLoader);得到所有的组件
  • 4.从META-INF/spring.factories位置来加载一个文件
    • 默认扫描我们当前系统里面所有META-INF/spring.factories位置的文件

    • spring-boot-autoconfigure-2.5.2.RELEASE.jar包里面也有META-INF/spring.factories
      在这里插入图片描述
      在这里插入图片描述

    • getCandidateConfigurations(annotationMetadata, attributes):获取所有的配置
      在这里插入图片描述
      在这里插入图片描述

		# Initializers
		org.springframework.context.ApplicationContextInitializer=\
		org.springframework.boot.autoconfigure.SharedMetadataReaderFactoryContextInitializer,\
		org.springframework.boot.autoconfigure.logging.ConditionEvaluationReportLoggingListener
		
		# Application Listeners
		org.springframework.context.ApplicationListener=\
		org.springframework.boot.autoconfigure.BackgroundPreinitializer
		
		# Environment Post Processors
		org.springframework.boot.env.EnvironmentPostProcessor=\
		org.springframework.boot.autoconfigure.integration.IntegrationPropertiesEnvironmentPostProcessor
		
		# Auto Configuration Import Listeners
		org.springframework.boot.autoconfigure.AutoConfigurationImportListener=\
		org.springframework.boot.autoconfigure.condition.ConditionEvaluationReportAutoConfigurationImportListener
		
		# Auto Configuration Import Filters
		org.springframework.boot.autoconfigure.AutoConfigurationImportFilter=\
		org.springframework.boot.autoconfigure.condition.OnBeanCondition,\
		org.springframework.boot.autoconfigure.condition.OnClassCondition,\
		org.springframework.boot.autoconfigure.condition.OnWebApplicationCondition
		
		# Auto Configure
		org.springframework.boot.autoconfigure.EnableAutoConfiguration=\
		org.springframework.boot.autoconfigure.admin.SpringApplicationAdminJmxAutoConfiguration,\
		org.springframework.boot.autoconfigure.aop.AopAutoConfiguration,\
		org.springframework.boot.autoconfigure.amqp.RabbitAutoConfiguration,\
		org.springframework.boot.autoconfigure.batch.BatchAutoConfiguration,\
		org.springframework.boot.autoconfigure.cache.CacheAutoConfiguration,\
		org.springframework.boot.autoconfigure.cassandra.CassandraAutoConfiguration,\
		org.springframework.boot.autoconfigure.context.ConfigurationPropertiesAutoConfiguration,\
		org.springframework.boot.autoconfigure.context.LifecycleAutoConfiguration,\
		org.springframework.boot.autoconfigure.context.MessageSourceAutoConfiguration,\
		org.springframework.boot.autoconfigure.context.PropertyPlaceholderAutoConfiguration,\
		org.springframework.boot.autoconfigure.couchbase.CouchbaseAutoConfiguration,\
		org.springframework.boot.autoconfigure.dao.PersistenceExceptionTranslationAutoConfiguration,\
		org.springframework.boot.autoconfigure.data.cassandra.CassandraDataAutoConfiguration,\
		org.springframework.boot.autoconfigure.data.cassandra.CassandraReactiveDataAutoConfiguration,\
		org.springframework.boot.autoconfigure.data.cassandra.CassandraReactiveRepositoriesAutoConfiguration,\
		org.springframework.boot.autoconfigure.data.cassandra.CassandraRepositoriesAutoConfiguration,\
		org.springframework.boot.autoconfigure.data.couchbase.CouchbaseDataAutoConfiguration,\
		org.springframework.boot.autoconfigure.data.couchbase.CouchbaseReactiveDataAutoConfiguration,\
		org.springframework.boot.autoconfigure.data.couchbase.CouchbaseReactiveRepositoriesAutoConfiguration,\
		org.springframework.boot.autoconfigure.data.couchbase.CouchbaseRepositoriesAutoConfiguration,\
		org.springframework.boot.autoconfigure.data.elasticsearch.ElasticsearchDataAutoConfiguration,\
		org.springframework.boot.autoconfigure.data.elasticsearch.ElasticsearchRepositoriesAutoConfiguration,\
		org.springframework.boot.autoconfigure.data.elasticsearch.ReactiveElasticsearchRepositoriesAutoConfiguration,\
		org.springframework.boot.autoconfigure.data.elasticsearch.ReactiveElasticsearchRestClientAutoConfiguration,\
		org.springframework.boot.autoconfigure.data.jdbc.JdbcRepositoriesAutoConfiguration,\
		org.springframework.boot.autoconfigure.data.jpa.JpaRepositoriesAutoConfiguration,\
		org.springframework.boot.autoconfigure.data.ldap.LdapRepositoriesAutoConfiguration,\
		org.springframework.boot.autoconfigure.data.mongo.MongoDataAutoConfiguration,\
		org.springframework.boot.autoconfigure.data.mongo.MongoReactiveDataAutoConfiguration,\
		org.springframework.boot.autoconfigure.data.mongo.MongoReactiveRepositoriesAutoConfiguration,\
		org.springframework.boot.autoconfigure.data.mongo.MongoRepositoriesAutoConfiguration,\
		org.springframework.boot.autoconfigure.data.neo4j.Neo4jDataAutoConfiguration,\
		org.springframework.boot.autoconfigure.data.neo4j.Neo4jReactiveDataAutoConfiguration,\
		org.springframework.boot.autoconfigure.data.neo4j.Neo4jReactiveRepositoriesAutoConfiguration,\
		org.springframework.boot.autoconfigure.data.neo4j.Neo4jRepositoriesAutoConfiguration,\
		org.springframework.boot.autoconfigure.data.r2dbc.R2dbcDataAutoConfiguration,\
		org.springframework.boot.autoconfigure.data.r2dbc.R2dbcRepositoriesAutoConfiguration,\
		org.springframework.boot.autoconfigure.data.redis.RedisAutoConfiguration,\
		org.springframework.boot.autoconfigure.data.redis.RedisReactiveAutoConfiguration,\
		org.springframework.boot.autoconfigure.data.redis.RedisRepositoriesAutoConfiguration,\
		org.springframework.boot.autoconfigure.data.rest.RepositoryRestMvcAutoConfiguration,\
		org.springframework.boot.autoconfigure.data.web.SpringDataWebAutoConfiguration,\
		org.springframework.boot.autoconfigure.elasticsearch.ElasticsearchRestClientAutoConfiguration,\
		org.springframework.boot.autoconfigure.flyway.FlywayAutoConfiguration,\
		org.springframework.boot.autoconfigure.freemarker.FreeMarkerAutoConfiguration,\
		org.springframework.boot.autoconfigure.groovy.template.GroovyTemplateAutoConfiguration,\
		org.springframework.boot.autoconfigure.gson.GsonAutoConfiguration,\
		org.springframework.boot.autoconfigure.h2.H2ConsoleAutoConfiguration,\
		org.springframework.boot.autoconfigure.hateoas.HypermediaAutoConfiguration,\
		org.springframework.boot.autoconfigure.hazelcast.HazelcastAutoConfiguration,\
		org.springframework.boot.autoconfigure.hazelcast.HazelcastJpaDependencyAutoConfiguration,\
		org.springframework.boot.autoconfigure.http.HttpMessageConvertersAutoConfiguration,\
		org.springframework.boot.autoconfigure.http.codec.CodecsAutoConfiguration,\
		org.springframework.boot.autoconfigure.influx.InfluxDbAutoConfiguration,\
		org.springframework.boot.autoconfigure.info.ProjectInfoAutoConfiguration,\
		org.springframework.boot.autoconfigure.integration.IntegrationAutoConfiguration,\
		org.springframework.boot.autoconfigure.jackson.JacksonAutoConfiguration,\
		org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration,\
		org.springframework.boot.autoconfigure.jdbc.JdbcTemplateAutoConfiguration,\
		org.springframework.boot.autoconfigure.jdbc.JndiDataSourceAutoConfiguration,\
		org.springframework.boot.autoconfigure.jdbc.XADataSourceAutoConfiguration,\
		org.springframework.boot.autoconfigure.jdbc.DataSourceTransactionManagerAutoConfiguration,\
		org.springframework.boot.autoconfigure.jms.JmsAutoConfiguration,\
		org.springframework.boot.autoconfigure.jmx.JmxAutoConfiguration,\
		org.springframework.boot.autoconfigure.jms.JndiConnectionFactoryAutoConfiguration,\
		org.springframework.boot.autoconfigure.jms.activemq.ActiveMQAutoConfiguration,\
		org.springframework.boot.autoconfigure.jms.artemis.ArtemisAutoConfiguration,\
		org.springframework.boot.autoconfigure.jersey.JerseyAutoConfiguration,\
		org.springframework.boot.autoconfigure.jooq.JooqAutoConfiguration,\
		org.springframework.boot.autoconfigure.jsonb.JsonbAutoConfiguration,\
		org.springframework.boot.autoconfigure.kafka.KafkaAutoConfiguration,\
		org.springframework.boot.autoconfigure.availability.ApplicationAvailabilityAutoConfiguration,\
		org.springframework.boot.autoconfigure.ldap.embedded.EmbeddedLdapAutoConfiguration,\
		org.springframework.boot.autoconfigure.ldap.LdapAutoConfiguration,\
		org.springframework.boot.autoconfigure.liquibase.LiquibaseAutoConfiguration,\
		org.springframework.boot.autoconfigure.mail.MailSenderAutoConfiguration,\
		org.springframework.boot.autoconfigure.mail.MailSenderValidatorAutoConfiguration,\
		org.springframework.boot.autoconfigure.mongo.embedded.EmbeddedMongoAutoConfiguration,\
		org.springframework.boot.autoconfigure.mongo.MongoAutoConfiguration,\
		org.springframework.boot.autoconfigure.mongo.MongoReactiveAutoConfiguration,\
		org.springframework.boot.autoconfigure.mustache.MustacheAutoConfiguration,\
		org.springframework.boot.autoconfigure.neo4j.Neo4jAutoConfiguration,\
		org.springframework.boot.autoconfigure.netty.NettyAutoConfiguration,\
		org.springframework.boot.autoconfigure.orm.jpa.HibernateJpaAutoConfiguration,\
		org.springframework.boot.autoconfigure.quartz.QuartzAutoConfiguration,\
		org.springframework.boot.autoconfigure.r2dbc.R2dbcAutoConfiguration,\
		org.springframework.boot.autoconfigure.r2dbc.R2dbcTransactionManagerAutoConfiguration,\
		org.springframework.boot.autoconfigure.rsocket.RSocketMessagingAutoConfiguration,\
		org.springframework.boot.autoconfigure.rsocket.RSocketRequesterAutoConfiguration,\
		org.springframework.boot.autoconfigure.rsocket.RSocketServerAutoConfiguration,\
		org.springframework.boot.autoconfigure.rsocket.RSocketStrategiesAutoConfiguration,\
		org.springframework.boot.autoconfigure.security.servlet.SecurityAutoConfiguration,\
		org.springframework.boot.autoconfigure.security.servlet.UserDetailsServiceAutoConfiguration,\
		org.springframework.boot.autoconfigure.security.servlet.SecurityFilterAutoConfiguration,\
		org.springframework.boot.autoconfigure.security.reactive.ReactiveSecurityAutoConfiguration,\
		org.springframework.boot.autoconfigure.security.reactive.ReactiveUserDetailsServiceAutoConfiguration,\
		org.springframework.boot.autoconfigure.security.rsocket.RSocketSecurityAutoConfiguration,\
		org.springframework.boot.autoconfigure.security.saml2.Saml2RelyingPartyAutoConfiguration,\
		org.springframework.boot.autoconfigure.sendgrid.SendGridAutoConfiguration,\
		org.springframework.boot.autoconfigure.session.SessionAutoConfiguration,\
		org.springframework.boot.autoconfigure.security.oauth2.client.servlet.OAuth2ClientAutoConfiguration,\
		org.springframework.boot.autoconfigure.security.oauth2.client.reactive.ReactiveOAuth2ClientAutoConfiguration,\
		org.springframework.boot.autoconfigure.security.oauth2.resource.servlet.OAuth2ResourceServerAutoConfiguration,\
		org.springframework.boot.autoconfigure.security.oauth2.resource.reactive.ReactiveOAuth2ResourceServerAutoConfiguration,\
		org.springframework.boot.autoconfigure.solr.SolrAutoConfiguration,\
		org.springframework.boot.autoconfigure.sql.init.SqlInitializationAutoConfiguration,\
		org.springframework.boot.autoconfigure.task.TaskExecutionAutoConfiguration,\
		org.springframework.boot.autoconfigure.task.TaskSchedulingAutoConfiguration,\
		org.springframework.boot.autoconfigure.thymeleaf.ThymeleafAutoConfiguration,\
		org.springframework.boot.autoconfigure.transaction.TransactionAutoConfiguration,\
		org.springframework.boot.autoconfigure.transaction.jta.JtaAutoConfiguration,\
		org.springframework.boot.autoconfigure.validation.ValidationAutoConfiguration,\
		org.springframework.boot.autoconfigure.web.client.RestTemplateAutoConfiguration,\
		org.springframework.boot.autoconfigure.web.embedded.EmbeddedWebServerFactoryCustomizerAutoConfiguration,\
		org.springframework.boot.autoconfigure.web.reactive.HttpHandlerAutoConfiguration,\
		org.springframework.boot.autoconfigure.web.reactive.ReactiveWebServerFactoryAutoConfiguration,\
		org.springframework.boot.autoconfigure.web.reactive.WebFluxAutoConfiguration,\
		org.springframework.boot.autoconfigure.web.reactive.error.ErrorWebFluxAutoConfiguration,\
		org.springframework.boot.autoconfigure.web.reactive.function.client.ClientHttpConnectorAutoConfiguration,\
		org.springframework.boot.autoconfigure.web.reactive.function.client.WebClientAutoConfiguration,\
		org.springframework.boot.autoconfigure.web.servlet.DispatcherServletAutoConfiguration,\
		org.springframework.boot.autoconfigure.web.servlet.ServletWebServerFactoryAutoConfiguration,\
		org.springframework.boot.autoconfigure.web.servlet.error.ErrorMvcAutoConfiguration,\
		org.springframework.boot.autoconfigure.web.servlet.HttpEncodingAutoConfiguration,\
		org.springframework.boot.autoconfigure.web.servlet.MultipartAutoConfiguration,\
		org.springframework.boot.autoconfigure.web.servlet.WebMvcAutoConfiguration,\
		org.springframework.boot.autoconfigure.websocket.reactive.WebSocketReactiveAutoConfiguration,\
		org.springframework.boot.autoconfigure.websocket.servlet.WebSocketServletAutoConfiguration,\
		org.springframework.boot.autoconfigure.websocket.servlet.WebSocketMessagingAutoConfiguration,\
		org.springframework.boot.autoconfigure.webservices.WebServicesAutoConfiguration,\
		org.springframework.boot.autoconfigure.webservices.client.WebServiceTemplateAutoConfiguration
		
		# Failure analyzers
		org.springframework.boot.diagnostics.FailureAnalyzer=\
		org.springframework.boot.autoconfigure.data.redis.RedisUrlSyntaxFailureAnalyzer,\
		org.springframework.boot.autoconfigure.diagnostics.analyzer.NoSuchBeanDefinitionFailureAnalyzer,\
		org.springframework.boot.autoconfigure.flyway.FlywayMigrationScriptMissingFailureAnalyzer,\
		org.springframework.boot.autoconfigure.jdbc.DataSourceBeanCreationFailureAnalyzer,\
		org.springframework.boot.autoconfigure.jdbc.HikariDriverConfigurationFailureAnalyzer,\
		org.springframework.boot.autoconfigure.r2dbc.ConnectionFactoryBeanCreationFailureAnalyzer,\
		org.springframework.boot.autoconfigure.session.NonUniqueSessionRepositoryFailureAnalyzer
		
		# Template availability providers
		org.springframework.boot.autoconfigure.template.TemplateAvailabilityProvider=\
		org.springframework.boot.autoconfigure.freemarker.FreeMarkerTemplateAvailabilityProvider,\
		org.springframework.boot.autoconfigure.mustache.MustacheTemplateAvailabilityProvider,\
		org.springframework.boot.autoconfigure.groovy.template.GroovyTemplateAvailabilityProvider,\
		org.springframework.boot.autoconfigure.thymeleaf.ThymeleafTemplateAvailabilityProvider,\
		org.springframework.boot.autoconfigure.web.servlet.JspTemplateAvailabilityProvider
		
		# DataSource initializer detectors
		org.springframework.boot.sql.init.dependency.DatabaseInitializerDetector=\
		org.springframework.boot.autoconfigure.flyway.FlywayMigrationInitializerDatabaseInitializerDetector

3.2.按需开启自动配置项:

a.概述

  • 1.文件里面写死了spring-boot一启动就要给容器中加载的所有配置类xxxxAutoConfiguration);
  • 2.虽然场景的自动配置在springboot启动的时候都加载了,但还是按照条件配置规则(@Conditionalxxxxxxx)来进行启动,最终按需配置

b.条件配置规则举例分析

  • 1.下面是条件配置规则(@Conditionalxxxxxxx)来决定是否进行启动的举例:
    在这里插入图片描述
    在这里插入图片描述

c.修改默认配置:

  • 1.SpringBoot默认会在底层配好所有的组件。但是如果用户自己配置了以用户的优先
        @Bean
		@ConditionalOnBean(MultipartResolver.class)  //容器中有这个类型组件
		@ConditionalOnMissingBean(name = DispatcherServlet.MULTIPART_RESOLVER_BEAN_NAME) //容器中没有这个名字 multipartResolver 的组件
		public MultipartResolver multipartResolver(MultipartResolver resolver) {
            //给@Bean标注的方法传入了对象参数,这个参数的值就会从容器中找。
            //SpringMVC multipartResolver。防止有些用户配置的文件上传解析器不符合规范
			// Detect if the user has created a MultipartResolver but named it incorrectly
			return resolver;
		}
	给容器中加入了文件上传解析器;

3.3.总结:

  • 1.SpringBoot先加载所有的自动配置类 xxxxxAutoConfiguration
  • 2.每个自动配置类按照条件进行生效,默认都会绑定配置文件指定的值。xxxxProperties里面拿。xxxProperties和配置文件进行了绑定
  • 3.生效的配置类就会给容器中装配很多组件
  • 4.只要容器中有这些组件,相当于这些功能就有了
  • 5.定制化配置
    • 用户直接自己@Bean替换底层的组件
    • 用户去看这个组件是获取的配置文件什么值就去修改:
  • 6.xxxxxAutoConfiguration ---> 组件 ---> xxxxProperties里面拿值 ----> application.properties

3.4.SpringBoot开发时的最佳实践:

  • 1.引入场景依赖

  • 2.查看自动配置了哪些(选做):

    • 自己分析,引入场景对应的自动配置一般都生效了
    • 配置文件中debug=true开启自动配置报告:Negative(不生效)\Positive(生效)
      在这里插入图片描述
  • 3.查看是否需要修改

  • 4.自定义加入或者替换组件:@Bean、@Component。。。。。

  • 5.自定义器 XXXXXCustomizer

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值