简单来说就是:
引入相应的dependency就能自动向SpringApplicationContext中注入相关功能的bean。
其实道理很简单,将制定的自动装配类配置到META-INF下,再配合条件@Conditional就能达到看起来的效果即自动的注入,省去了大量配置
比如:
<dependency>
<groupId>com.riskgroupId>
<artifactId>distribute-design-spring-boot-starterartifactId>
<version>0.0.1-SNAPSHOTversion>
dependency>
上面的jar包是我们自定义的starter。
他看起来是一个普通的jar包(有点像公司的二方包),
先说步骤
再说注意事项或者叫做所谓的坑(实际是理解不深刻)。
我们以maven项目为例
分成如下的三个步骤:
- resource/META-INF/目录下建立文件spring.factories,并填写自动装配类
org.springframework.boot.autoconfigure.EnableAutoConfiguration=\
com.risk.distribute.design.lock.DistributeLockAutoConfiguration
其中DistributeLockAutoConfiguration
是@Configuration
注解标识的
- 打包成jar,在工程中引入打包成的jar
3 定义配置类
@Configuration //①来标识它是一个配置类
@ConditionalOnProperty(value = "distribute.lock.enable",havingValue = "true",matchIfMissing = true)
@Import({ZookeeperDistributeLockConfiguration.class,
RedisDistributeLockConfiguration.class})
@AutoConfigureAfter({RedisAutoConfiguration.class})//我们使用redisTemplate所以用的这个
public class DistributeLockAutoConfiguration {
//②这个配置类是往BeanFactory注入bean
@Bean
public LockTemplate<?> lockTemplate(DistributeLock distributeLock){
return new LockTemplate(distributeLock);
}
}
最主要的是要有①和②两个部分,其它是稍微高级一点的功能,它看起来就是如此这样简单。
简单解释一些稍微高级一点的功能:
当环境中有这个属性
注解 | 功能 | 案例功能 |
---|---|---|
@ConditionalOnProperty | 当Spring的Environment中有某个属性,且值=xxx条件 | 当环境中有distribute.lock.enable=true 条件成立或者没有这个属性则认为条件成立 |
Import | 往BeanFactory放入配置类,当然也得看配置类是否满足条件 | 这里直接导入两个配置类 |
AutoConfigureAfter | 外部的starter对应的配置类排序 | RedisAutoConfiguration在前面,先被Spring加载 |
大家自己根据自己的业务写一个配置类的时候有没有遇到一些问题?
上面的示例 是最基本的 但是在实际过程中可能会遇到如下的一些问题
带着这两个问题看下源码
一切始于我们的启动类注解@SpringbootApplication
注解
springApplication#run
AnnotationConfigServletWebServertApplicationContext#refresh
AbstractApplicationContext#invokeBeanFactoryPostProcessors
ConfigurationClassPostProcessor#postProcessBeanDefinitionRegistry
ConfigurationClassParser#parse
ConfigurationClassPostProcessor这个类BeanFactoryPostProcessor的子类 从名字可以看出他是专门处理 @Configuration标注的类的。
public void processConfigBeanDefinitions(BeanDefinitionRegistry registry) {
List<BeanDefinitionHolder> configCandidates = new ArrayList<>();
String[] candidateNames = registry.getBeanDefinitionNames();
for (String beanName : candidateNames) {
BeanDefinition beanDef = registry.getBeanDefinition(beanName);
if (ConfigurationClassUtils.isFullConfigurationClass(beanDef) ||
ConfigurationClassUtils.isLiteConfigurationClass(beanDef)) {
if (logger.isDebugEnabled()) {
logger.debug("Bean definition has already been processed as a configuration class: " + beanDef);
}
}
else if (ConfigurationClassUtils.checkConfigurationClassCandidate(beanDef, this.metadataReaderFactory)) {
//① 当前类上有@Configuration注解的 通常情况下是我们的启动类@SpringBootApplication 它里边包含@Configuration注解
configCandidates.add(new BeanDefinitionHolder(beanDef, beanName));
}
}
// Return immediately if no @Configuration classes were found
if (configCandidates.isEmpty()) {
return;
}
// Sort by previously determined @Order value, if applicable
configCandidates.sort((bd1, bd2) -> {
int i1 = ConfigurationClassUtils.getOrder(bd1.getBeanDefinition());
int i2 = ConfigurationClassUtils.getOrder(bd2.getBeanDefinition());
return Integer.compare(i1, i2);
});
// Detect any custom bean name generation strategy supplied through the enclosing application context
SingletonBeanRegistry sbr = null;
if (registry instanceof SingletonBeanRegistry) {
sbr = (SingletonBeanRegistry) registry;
if (!this.localBeanNameGeneratorSet) {
BeanNameGenerator generator = (BeanNameGenerator) sbr.getSingleton(CONFIGURATION_BEAN_NAME_GENERATOR);
if (generator != null) {
this.componentScanBeanNameGenerator = generator;
this.importBeanNameGenerator = generator;
}
}
}
if (this.environment == null) {
this.environment = new StandardEnvironment();
}
// ② 构建解析标注了@Configuration 的解析器
ConfigurationClassParser parser = new ConfigurationClassParser(
this.metadataReaderFactory, this.problemReporter, this.environment,
this.resourceLoader, this.componentScanBeanNameGenerator, registry);
Set<BeanDefinitionHolder> candidates = new LinkedHashSet<>(configCandidates);
Set<ConfigurationClass> alreadyParsed = new HashSet<>(configCandidates.size());
//③ 具体的解析逻辑,因为candidates为标注了@Configuration的类的BeanDefinition的集合(你项目中的),在解析的过程中还会产生
//一些 @Configuration标注的类 也会加入到这个集合中 --比如SPI方式自动装配进来一些类(通常是Starter中的)所以用了while的方式
do {
parser.parse(candidates);
parser.validate();
Set<ConfigurationClass> configClasses = new LinkedHashSet<>(parser.getConfigurationClasses());
configClasses.removeAll(alreadyParsed);
// Read the model and create bean definitions based on its content
if (this.reader == null) {
this.reader = new ConfigurationClassBeanDefinitionReader(
registry, this.sourceExtractor, this.resourceLoader, this.environment,
this.importBeanNameGenerator, parser.getImportRegistry());
}
//④ 加载configClasses 主要关注 @Import @Bean部分 这些部分注册到BeanDefinitionRegistry
this.reader.loadBeanDefinitions(configClasses);
alreadyParsed.addAll(configClasses);
candidates.clear();
if (registry.getBeanDefinitionCount() > candidateNames.length) {
String[] newCandidateNames = registry.getBeanDefinitionNames();
Set<String> oldCandidateNames = new HashSet<>(Arrays.asList(candidateNames));
Set<String> alreadyParsedClasses = new HashSet<>();
for (ConfigurationClass configurationClass : alreadyParsed) {
alreadyParsedClasses.add(configurationClass.getMetadata().getClassName());
}
for (String candidateName : newCandidateNames) {
if (!oldCandidateNames.contains(candidateName)) {
BeanDefinition bd = registry.getBeanDefinition(candidateName);
if (ConfigurationClassUtils.checkConfigurationClassCandidate(bd, this.metadataReaderFactory) &&
!alreadyParsedClasses.contains(bd.getBeanClassName())) {
candidates.add(new BeanDefinitionHolder(bd, candidateName));
}
}
}
candidateNames = newCandidateNames;
}
}
while (!candidates.isEmpty());
if (sbr != null && !sbr.containsSingleton(IMPORT_REGISTRY_BEAN_NAME)) {
sbr.registerSingleton(IMPORT_REGISTRY_BEAN_NAME, parser.getImportRegistry());
}
if (this.metadataReaderFactory instanceof CachingMetadataReaderFactory) {
((CachingMetadataReaderFactory) this.metadataReaderFactory).clearCache();
}
}
上面的代码分开来看
① 获取所有的有@Configuration标注的类的BeanDefinition ,并进行排序
从BeanDefinitionRegistry
获取已经扫描并转变为BeanDefinition的集合,进行循环判断类上面是否有@Configuration注解正常来说只有我们的启动类@SpringBootApplication中包含@Configuration注解
② 构建解析标注了@Configuration 的解析器 ConfigurationClassParser
③ 具体的解析逻辑,parser#parse(configurationClasses) 因为candidates为标注了@Configuration的类的BeanDefinition的集合(你项目中的),在解析的过程中还会产生一些 @Configuration标注的类 也会加入到这个集合中 --比如SPI方式自动装配进来一些类(通常是Starter中的)所以用了while的方式
④ 加载configClasses 主要关注 @Import @Bean部分 这些部分注册到BeanDefinitionRegistry
第三步就是我们的重点了
重点类ConfigurationClassParser 简单记录下比较重要的成员属性
class ConfigurationClassParser {
private final BeanDefinitionRegistry registry;
private final ComponentScanAnnotationParser componentScanParser;
private final ConditionEvaluator conditionEvaluator;
private final Map<ConfigurationClass, ConfigurationClass;
private final DeferredImportSelectorHandler deferredImportSelectorHandler = new DeferredImportSelectorHandler();
}
解析@Configuration标注配置类ConfigurationClassParser#parse(Set< BeanDefinitionHolder > configCandidates)
public void parse(Set<BeanDefinitionHolder> configCandidates) {
for (BeanDefinitionHolder holder : configCandidates) {
BeanDefinition bd = holder.getBeanDefinition();
//去掉了try catch
parse(((AnnotatedBeanDefinition) bd).getMetadata(), holder.getBeanName());
this.deferredImportSelectorHandler.process();
}
protected final void parse(AnnotationMetadata metadata, String beanName) throws IOException {
processConfigurationClass(new ConfigurationClass(metadata, beanName));
//每个@Configuraiton的元数据和名字包装成了ConfigurationClass类
}
特别说明:到目前为止 这里的configCandidates是来自于【启动类和当前项目】中你手工添加的@Configuration的类
protected void processConfigurationClass(ConfigurationClass configClass) throws IOException {
//① 评估是否需要跳过@Configuration标注的类 依据 有@Conditional
if (this.conditionEvaluator.shouldSkip(configClass.getMetadata(), ConfigurationPhase.PARSE_CONFIGURATION)) {
return;
}
ConfigurationClass existingClass = this.configurationClasses.get(configClass);
if (existingClass != null) {
if (configClass.isImported()) {
if (existingClass.isImported()) {
existingClass.mergeImportedBy(configClass);
}
// Otherwise ignore new imported config class; existing non-imported class overrides it.
return;
}
else {
// Explicit bean definition found, probably replacing an import.
// Let's remove the old one and go with the new one.
this.configurationClasses.remove(configClass);
this.knownSuperclasses.values().removeIf(configClass::equals);
}
}
// Recursively process the configuration class and its superclass hierarchy.
SourceClass sourceClass = asSourceClass(configClass);
do {
sourceClass = doProcessConfigurationClass(configClass, sourceClass);
}
while (sourceClass != null);
this.configurationClasses.put(configClass, configClass);
}
① 评估是否需要跳过@Configuration标注的类 ,依据conditionEvaluator#shouldSkip()方法的实现逻辑
没有@Conditional 的就不跳过
有@Conditional的判断 将所有的@Conditional集合起来进行排序
只要有一个条件不通过
跳过去 不对当前配置类记性解析了,通过就不跳过
第①处代码如下:
public boolean shouldSkip(@Nullable AnnotatedTypeMetadata metadata, @Nullable ConfigurationPhase phase) {
if (metadata == null || !metadata.isAnnotated(Conditional.class.getName())) {
return false;
}
if (phase == null) {
if (metadata instanceof AnnotationMetadata &&
ConfigurationClassUtils.isConfigurationCandidate((AnnotationMetadata) metadata)) {
return shouldSkip(metadata, ConfigurationPhase.PARSE_CONFIGURATION);
}
return shouldSkip(metadata, ConfigurationPhase.REGISTER_BEAN);
}
List<Condition> conditions = new ArrayList<>();
for (String[] conditionClasses : getConditionClasses(metadata)) {
for (String conditionClass : conditionClasses) {
Condition condition = getCondition(conditionClass, this.context.getClassLoader());
conditions.add(condition);
}
}
//将@Configuration标注的类上 所有的@Conditional集合起来记性排序
AnnotationAwareOrderComparator.sort(conditions);
for (Condition condition : conditions) {
ConfigurationPhase requiredPhase = null;
if (condition instanceof ConfigurationCondition) {
requiredPhase = ((ConfigurationCondition) condition).getConfigurationPhase();
}
if ((requiredPhase == null || requiredPhase == phase) && !condition.matches(this.context, metadata)) {//只要有一个条件不满足就skip调
return true;
}
}
return false;
}
第②处代码:
@Nullable
protected final SourceClass doProcessConfigurationClass(ConfigurationClass configClass, SourceClass sourceClass)
throws IOException {
// 删除部分不重要的代码
Set<AnnotationAttributes> componentScans = AnnotationConfigUtils.attributesForRepeatable(
sourceClass.getMetadata(), ComponentScans.class, ComponentScan.class);
if (!componentScans.isEmpty() &&
!this.conditionEvaluator.shouldSkip(sourceClass.getMetadata(), ConfigurationPhase.REGISTER_BEAN)) {
for (AnnotationAttributes componentScan : componentScans) {
// The config class is annotated with @ComponentScan -> perform the scan immediately
Set<BeanDefinitionHolder> scannedBeanDefinitions =
this.componentScanParser.parse(componentScan, sourceClass.getMetadata().getClassName());
// Check the set of scanned definitions for any further config classes and parse recursively if needed
for (BeanDefinitionHolder holder : scannedBeanDefinitions) {
BeanDefinition bdCand = holder.getBeanDefinition().getOriginatingBeanDefinition();
if (bdCand == null) {
bdCand = holder.getBeanDefinition();
}
if (ConfigurationClassUtils.checkConfigurationClassCandidate(bdCand, this.metadataReaderFactory)) {
parse(bdCand.getBeanClassName(), holder.getBeanName());
}
}
}
}
// Process any @Import annotations
processImports(configClass, sourceClass, getImports(sourceClass), true);
// Process any @ImportResource annotations
AnnotationAttributes importResource =
AnnotationConfigUtils.attributesFor(sourceClass.getMetadata(), ImportResource.class);
if (importResource != null) {
String[] resources = importResource.getStringArray("locations");
Class<? extends BeanDefinitionReader> readerClass = importResource.getClass("reader");
for (String resource : resources) {
String resolvedResource = this.environment.resolveRequiredPlaceholders(resource);
configClass.addImportedResource(resolvedResource, readerClass);
}
}
// Process individual @Bean methods
Set<MethodMetadata> beanMethods = retrieveBeanMethodMetadata(sourceClass);
for (MethodMetadata methodMetadata : beanMethods) {
configClass.addBeanMethod(new BeanMethod(methodMetadata, configClass));
}
// Process default methods on interfaces
processInterfaces(configClass, sourceClass);
// Process superclass, if any
if (sourceClass.getMetadata().hasSuperClass()) {
String superclass = sourceClass.getMetadata().getSuperClassName();
if (superclass != null && !superclass.startsWith("java") &&
!this.knownSuperclasses.containsKey(superclass)) {
this.knownSuperclasses.put(superclass, configClass);
// Superclass found, return its annotation metadata and recurse
return sourceClass.getSuperClass();
}
}
// No superclass -> processing is complete
return null;
}