SpringBoot 自动配置

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

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

再进入getCandidateConfigurations()方法,

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

再进入loadFactoryNames()方法,

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

再进入loadSpringFactories()方法,

Enumeration 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 自动配置)