[关闭]
@zhuanxu 2017-11-23T09:18:47.000000Z 字数 882 阅读 1720

Spring Boot @EnableAutoConfiguration 深入分析

spring-boot


@EnableAutoConfiguration 的作用:从classpath中搜索所有配置文件,将其中key=org.springframework.boot.autoconfigure.EnableAutoConfiguration对应的配置项加载到Spring容器中。

其内部实现的关键点:
1. ImportSelector接口
2. SpringFactoriesLoader 从“META-INF/spring.factories” 中读取key为org.springframework.boot.autoconfigure.EnableAutoConfiguration的值,并将其加载进入容器
3. 读取spring.boot.enableautoconfiguration的值,为true才开启自动配置,默认为true

看一个稍微详细的分析:

  1. class EnableAutoConfigurationImportSelector
  2. selectImports
  3. 判断"spring.boot.enableautoconfiguration" 是否为true
  4. // 获取配置类
  5. SpringFactoriesLoader.loadFactoryNames(EnableAutoConfiguration.class)
  6. 根据key读取 "META-INF/spring.factories" 中的value

看一个spring-boot的配置org.springframework.boot.autoconfigure.gson.GsonAutoConfiguration,配合Condition能够实现按需加载。

  1. @Configuration
  2. @ConditionalOnClass(Gson.class)
  3. public class GsonAutoConfiguration {
  4. @Bean
  5. @ConditionalOnMissingBean
  6. public Gson gson() {
  7. return new Gson();
  8. }
  9. }
添加新批注
在作者公开此批注前,只有你和作者可见。
回复批注