问题:我们并未写类似kafka的配置类,SpringBoot是如何导入配置的呢?
- 打开
@SpringBootApplication可看到@EnableAutoConfiguration,即开启自动配置功能 - 打开
@EnableAutoConfiguration可看到@Import(AutoConfigurationImportSelector.class),即导入了AutoConfigurationImportSelector.class类,自动配置导入选择器。 - 再看
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模块的自动配置文件的全目录
-
答:SpringBoot在
spring-boot-autoconfigure-2.0.4.RELEASE.jar里面准备好了所有的配置类,在启动的时候,可以自动导入所有配置。以前需要自己手动写的配置类就不用写了(有自动配置类没有的配置还是要自定义)。









网友评论