首先我们看看@EnableAutoConfiguration定义的源码:
@Target(ElementType.TYPE) @Retention(RetentionPolicy.RUNTIME) @Documented @Inherited @SpringBootConfiguration @EnableAutoConfiguration @ComponentScan(excludeFilters = { @Filter(type = FilterType.CUSTOM, classes = TypeExcludeFilter.class), @Filter(type = FilterType.CUSTOM, classes = AutoConfigurationExcludeFilter.class) }) public @interface SpringBootApplication {
其中有一个EnableAutoConfiguration,代表开启了自动配置,我们再深入一层,看看@EnableAutoConfiguration的源码:
@Target(ElementType.TYPE) @Retention(RetentionPolicy.RUNTIME) @Documented @Inherited @AutoConfigurationPackage @Import(AutoConfigurationImportSelector.class) public @interface EnableAutoConfiguration {
这里我们可以看到@Import(AutoConfigurationImportSelector.class),这个AutoConfigurationImportSelector其实就是spring用来引入自动配置类的一个手段。AutoConfigurationImportSelector里面又有下面这段代码:
protected List<String> getCandidateConfigurations(AnnotationMetadata metadata, AnnotationAttributes attributes) { List<String> configurations = SpringFactoriesLoader.loadFactoryNames(getSpringFactoriesLoaderFactoryClass(), getBeanClassLoader()); Assert.notEmpty(configurations, "No auto configuration classes found in META-INF/spring.factories. If you " + "are using a custom packaging, make sure that file is correct."); return configurations; }
可以看到,它是从META-INF/spring.factories查询自动配置类的,如果没有查到会报错。
所以,spring.factories一个功能是写入spring需要引入的类绝对名,自动配置类就是在这里面写着,下面我截取一段spring.factories的内容:
# 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,\ ......
然后@EnableAutoConfiguration与spring.factories的关系,就是@EnableAutoConfiguration使用了spring.factories文件内配置的自动配置类信息来加载需要的自动配置类。
原创文章,作者:geekgao,如若转载,请注明出处:https://www.geekgao.cn/archives/2096