共计 2295 个字符,预计需要花费 6 分钟才能阅读完成。
一、主动配置的作用
1. 将第三方的组件主动装载到 IOC 容器外面,不须要开发人员再去编写相干的配置,比如说咱们在 pom.xml 中增加启动器 spring-boot-starter-data-redis 之后,咱们就能够间接应用 @Autowired 来注入 RedisTemplate,这就是主动配置的益处。
2. 本文波及到 @Import 注解的应用、SpringFactories 机制
二、主动配置的原理
1. 首先他是通过启动类上的 @SpringBootApplication 实现的,其中蕴含两个注解 @SpringBootConfiguration、@EnableAutoConfiguration,而 @SpringBootConfiguration 能够看做 @Configuration 注解,次要实现主动配置的注解是 @EnableAutoConfiguration
2. 应用 @Import 并定义 AutoConfigurationImportSelector 来实现批量注册(不晓得 @Import 作用的同学倡议查一下该注解),而后咱们点进去其中有个 getAutoConfigurationEntry
public String[] selectImports(AnnotationMetadata annotationMetadata) {if (!this.isEnabled(annotationMetadata)) {return NO_IMPORTS;} else {AutoConfigurationImportSelector.AutoConfigurationEntry autoConfigurationEntry = this.getAutoConfigurationEntry(annotationMetadata);
return StringUtils.toStringArray(autoConfigurationEntry.getConfigurations());
}
}
3. 进入该办法 getCandidateConfigurations
protected AutoConfigurationImportSelector.AutoConfigurationEntry getAutoConfigurationEntry(AnnotationMetadata annotationMetadata) {if (!this.isEnabled(annotationMetadata)) {return EMPTY_ENTRY;} else {AnnotationAttributes attributes = this.getAttributes(annotationMetadata);
List<String> configurations = this.getCandidateConfigurations(annotationMetadata, attributes);
configurations = this.removeDuplicates(configurations);
Set<String> exclusions = this.getExclusions(annotationMetadata, attributes);
this.checkExcludedClasses(configurations, exclusions);
configurations.removeAll(exclusions);
configurations = this.getConfigurationClassFilter().filter(configurations);
this.fireAutoConfigurationImportEvents(configurations, exclusions);
return new AutoConfigurationImportSelector.AutoConfigurationEntry(configurations, exclusions);
}
}
4. 能够看到他调用了 SpringFactoriesLoader.loadFactoryNames 办法,最终调用该类的 loadSpringFactories,该办法能够让 ClassLoader 读取所有的 jar 包下的 META-INF/spring.factories 下的文件信息,该文件蕴含了第三方 jar 包所提供的 @Configuration 配置类的全限定类名
protected List<String> getCandidateConfigurations(AnnotationMetadata metadata, AnnotationAttributes attributes) {List<String> configurations = SpringFactoriesLoader.loadFactoryNames(this.getSpringFactoriesLoaderFactoryClass(), this.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;
}
5. 如在 Spring-boot-autoconfigure 模块的 spring.factories 中