美文网首页
SpringBoot 自动配置

SpringBoot 自动配置

作者: steamed_bun | 来源:发表于2020-05-27 15:25 被阅读0次

问题:我们并未写类似kafka的配置类,SpringBoot是如何导入配置的呢?

  1. 打开@SpringBootApplication可看到@EnableAutoConfiguration,即开启自动配置功能
  2. 打开@EnableAutoConfiguration可看到@Import(AutoConfigurationImportSelector.class),即导入了AutoConfigurationImportSelector.class类,自动配置导入选择器。
  3. 再看selectImports方法,
List<String> configurations = getCandidateConfigurations(annotationMetadata,
                attributes);

再进入getCandidateConfigurations()方法,

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

再进入loadFactoryNames()方法,

loadSpringFactories(classLoader).getOrDefault(factoryClassName, 
                Collections.emptyList());

再进入loadSpringFactories()方法,

Enumeration<URL> urls = (classLoader != null ?
                    classLoader.getResources(FACTORIES_RESOURCE_LOCATION) :
                    ClassLoader.getSystemResources(FACTORIES_RESOURCE_LOCATION));

可看到

public static final String FACTORIES_RESOURCE_LOCATION = "META-INF/spring.factories";

spring-boot-autoconfigure-2.0.4.RELEASE.jar!/META-INF/spring.factories可看到,里面有springboot模块的自动配置文件的全目录

  1. :SpringBoot在spring-boot-autoconfigure-2.0.4.RELEASE.jar里面准备好了所有的配置类,在启动的时候,可以自动导入所有配置。以前需要自己手动写的配置类就不用写了(有自动配置类没有的配置还是要自定义)。

相关文章

网友评论

      本文标题:SpringBoot 自动配置

      本文链接:https://www.haomeiwen.com/subject/dxfwahtx.html