springboot(4)——自动配置原理

1 详解源码过程

在这里插入图片描述点击注解:@SpringBootApplication程序的主入口
在这里插入图片描述
注解:@SpringBootConfiguration @EnableAutoConfiguration
特别注意:@EnableAutoConfiguration 自动导入配置
点击注解:@EnableAutoConfiguration
在这里插入图片描述
注解:@Import(AutoConfigurationImportSelector.class)
在这里插入图片描述
在这里插入图片描述
注意:List<String> configurations = getCandidateConfigurations(annotationMetadata, attributes); 候选配置
在这里插入图片描述
点击:loadFactoryNames
在这里插入图片描述
在这里插入图片描述
注意:FACTORIES_RESOURCE_LOCATION
在这里插入图片描述
得到:public static final String FACTORIES_RESOURCE_LOCATION = "META-INF/spring.factories";
在这里插入图片描述

2 配置文件是如何操作

spring.factories中,我们找到启动器org.springframework.boot.autoconfigure.web.servlet.HttpEncodingAutoConfiguration,\进入HttpEncodingAutoConfiguration可以看到在这里插入图片描述
自动绑定属性@EnableConfigurationProperties(ServerProperties.class)点击可以看到在这里插入图片描述
我们可以通过配置文件application.yaml来修改
在这里插入图片描述
点击private final Encoding encoding = new Encoding();即可得到
在这里插入图片描述
配置文件到底可以写什么? 和spring.factories有什么联系?
xxxAutoConfiguration:默认值 xxxProperties和配置文件绑定,我就可以使用自定义的配置了。

一但这个配置类生效;这个配置类就会给容器中添加各种组件;
这些组件的属性是从对应的properties类中获取的,这些类里面的每一个属性又是和配置文件绑定的;
所有在配置文件中能配置的属性都是在xxxxProperties类中封装着;
配置文件能配置什么就可以参照某个功能对应的这个属性类

1、SpringBoot启动会加载大量的自动配置类
2、我们看我们需要的功能有没有在SpringBoot默认写好的自动配置类当中;
3、我们再来看这个自动配置类中到底配置了哪些组件;(只要我们要用的组件存在在其中,我们就不需要再手动配置了)
4、给容器中自动配置类添加组件的时候,会从properties类中获取某些属性。我们只需要在配置文件中指定这些属性的值即可;
xxxxAutoConfigurartion:自动配置类;给容器中添加组件
xxxxProperties:封装配置文件中相关属性;

猜你喜欢

转载自blog.csdn.net/zs18753479279/article/details/112426413