SpringBoot自动配置原理

自动配置原理:

1)、SpringBoot启动的时候加载主配置类,开启了自动配置功能@EnableAutoConfiguration

2)、@EnableAutoConfiguration的作用

  利用EnableAutoConfigurationImportSelector给容器中导入一些组件

  可以查看selectImports方法的内容:

  List<String> configurations = this.getCandidateConfigurations(annotationMetadata, attributes); 获取候选的配置

 List<String> configurations = SpringFactoriesLoader.loadFactoryNames(this.getSpringFactoriesLoaderFactoryClass(), this.getBeanClassLoader());

  扫描jar包下类路径的MEAT-INF/spring.factories

private static final Log logger = LogFactory.getLog(SpringFactoriesLoader.class);

  把扫描到的这些文件的内容包装成properties对象

Enumeration<URL> urls = (classLoader != null ? classLoader.getResources(FACTORIES_RESOURCE_LOCATION) :
					ClassLoader.getSystemResources(FACTORIES_RESOURCE_LOCATION));
			List<String> result = new ArrayList<String>();
			while (urls.hasMoreElements()) {
				URL url = urls.nextElement();
				Properties properties = PropertiesLoaderUtils.loadProperties(new UrlResource(url));
				String factoryClassNames = properties.getProperty(factoryClassName);
				result.addAll(Arrays.asList(StringUtils.commaDelimitedListToStringArray(factoryClassNames)));
			}

  从properties中获取到EnableAutoConfiguration.class类的类名对应的值,然后把他们添加在容器中

将类路径下META-INF/spring.factories里面配置的所有EnableAutoConfiguration的值加入到容器中

 每一个在spring.factories中的xxxAutoConfiguration类都是容器中的一个组件,都加入到容器中,用他们来自动配置

3)每一个自动配置类进行自动配置

4)以HttpEncodingAutoConfiguration(Http编码自动配置)来例来解释自动配置原理

@Configuration  //表示这是一个配置类,可以给容器中添加组件
@EnableConfigurationProperties({HttpEncodingProperties.class}) //启动指定类的ConfigurationProperties功能,将配置文件中对应的值和
                                      //和HttpEncodingProperties绑定起来
@ConditionalOnWebApplication    //spring底层是@Configuration注解,根据不同条件判断,如果满足条件,则注解生效,判断当前应用是否为web应用,如果是,
                      //当前配置类生效        
@ConditionalOnClass({CharacterEncodingFilter.class}) //判断当前项目有没有这个类CharacterEncodingFilter
@ConditionalOnProperty(        //从配置文件中获取指定值和bean的属性进行绑定 
prefix = "spring.http.encoding",     //判断配置文件中是否存在某个配置,Spring.http.encoding.enabled;如果不存在,判断也是成立的
value = {"enabled"}, matchIfMissing = true )
public class HttpEncodingAutoConfiguration {
private final HttpEncodingProperties properties;

 5)、所有在配置文件中能配置的属性都是在xxxProperties类中封装着,配置文件能配置成什么就可以参照某一个功能对应这个属性类

@ConditionalOnProperty(
    prefix = "spring.http.encoding",
    value = {"enabled"},
    matchIfMissing = true
)
public class HttpEncodingAutoConfiguration {

  

原文地址:https://www.cnblogs.com/ghwq/p/12881745.html