@SpringBootApplication里面三个核心注解
@SpringBootConfiguration表明该类为配置类
@EnableAutoConfiguration //开启springBoot自动配置 里面有两个关键注解
@ComponentScan //扫描该类所在包下spring的注解
进入@EnableAutoConfiguration 发现
@AutoConfigurationPackage //该注解表明 此类所在包为自动配置包进行管理
@Import(AutoConfigurationImportSelector.class)
//该注解表明 此类所在包为自动配置包进行管理
@AutoConfigurationPackage
@Import(AutoConfigurationImportSelector.class)
public @interface EnableAutoConfiguration {
@SpringBootApplication注解点进去,集成了@EnableAutoConfiguration注解,而这个注解中使用了@Import(AutoConfigurationImportSelector.class)。点进AutoConfigurationImportSelector,然后在getCandidateConfigurations方法中去获取配置信息,继续往里追
getAutoConfigurationEntry()
protected AutoConfigurationEntry getAutoConfigurationEntry(AnnotationMetadata annotationMetadata) {
if (!isEnabled(annotationMetadata)) {
return EMPTY_ENTRY;
}
AnnotationAttributes attributes = getAttributes(annotationMetadata);
//继续追该方法
List<String> configurations = getCandidateConfigurations(annotationMetadata, attributes);
进入getCandidateConfigurations找到loadSpringFactories()方法
private static Map<String, List<String>> loadSpringFactories(ClassLoader classLoader) {
Map<String, List<String>> result = cache.get(classLoader);
if (result != null) {
return result;
}
result = new HashMap<>();
try {
//关键一句
Enumeration<URL> urls = classLoader.getResources(FACTORIES_RESOURCE_LOCATION);
此时FACTORIES_RESOURCE_LOCATION = "META-INF/spring.factories";
就是获取所有start依赖包下的spring.factories 然后其中内容就是自动配置包的全限定名称,拿到这些全限定名称之后通过反射调用,完成自动装配。
此时会扫描所有的自动配置类,但是不一定会初始化成功,原因为自动配置类中@Conditional 注解,效果为满足条件配置才会生效。
随便进入一个自动配置类看看
@Configuration(proxyBeanMethods = false)
@AutoConfigureAfter(JacksonAutoConfiguration.class)
//假设没有注册Cluster 则此次注册就不会生效
@ConditionalOnClass(Cluster.class)
@ConditionalOnProperty("spring.couchbase.connection-string")
@EnableConfigurationProperties(CouchbaseProperties.class)
public class CouchbaseAutoConfiguration {
最后完成springBoot自动装配。