自动配置-Conditional

SpringBoot的派生条件注解

我们都知道,SpringBoot自动配置是需要满足相应的条件才会自动配置,因此SpringBoot的自动配置大量应用了条件注解ConditionalOnXXX。如下图:

那么上图的条件注解如何使用呢?

举个栗子,我们来看下如何使用@ConditionalOnClass@ConditionalOnProperty这两个注解,先看下图代码:

HelloWorldEnableAutoConfiguration这个自动配置类应用了@ConditionalOnClassConditionalOnProperty两个条件注解,那么只有在满足:classpath中存在HelloWorldComponent.class和配置了hello.world.namehello.world.age属性这两个条件的情况下才会创建HelloWorldComponent这个bean

其实SpringBoot的@ConditionalOnXXX等条件注解都是派生注解,那么什么是派生注解呢? 就拿上面的栗子来说,以@ConditionalOnClass(HelloWorldComponent.class)为例,我们打开ConditionalOnClass注解源码,如下:

@Target({ ElementType.TYPE, ElementType.METHOD })
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Conditional(OnClassCondition.class)
public @interface ConditionalOnClass {

	Class<?>[] value() default {};

	String[] name() default {};

}

可以看到@ConditionalOnClass注解上面又标注了@Conditional(OnClassCondition.class)注解,因此@ConditionalOnClass@Conditional的派生注解,@Conditional(OnClassCondition.class)@ConditionalOnClass注解是等价的,即这两个注解标注在某个配置类上的效果是等价的。

而SpringBoot的自动配置原理正是建立在这些大量的派生条件注解@ConditionalOnXXX之上,而这些条件注解的原理跟Spring的Condition接口有关。因此我们先来研究下Condition接口的相关源码。

Condition接口

Condition接口源码分析

分析Condition接口源码前先看下如何自定义ConditionalOnXXX注解,举个栗子,比如自定义一个@ConditionalOnLinux注解,该注解只有在其属性environment是"linux"才会创建相关的bean。定义了以下代码:

/**
 * 实现spring 的Condition接口,并且重写matches()方法,如果@ConditionalOnLinux的注解属性environment是linux就返回true
 *
 */
public class LinuxCondition implements Condition {

	@Override
	public boolean matches(ConditionContext context, AnnotatedTypeMetadata metadata) {
		// 获得注解@ConditionalOnLinux的所有属性
		List<AnnotationAttributes> allAnnotationAttributes = annotationAttributesFromMultiValueMap(
				metadata.getAllAnnotationAttributes(
						ConditionalOnLinux.class.getName()));
		for (AnnotationAttributes annotationAttributes : allAnnotationAttributes) {
			// 获得注解@ConditionalOnLinux的environment属性
			String environment = annotationAttributes.getString("environment");
			// 若environment等于linux,则返回true
			if ("linux".equals(environment)) {
				return true;
			}
		}
		return false;
	}
}
@Target({ ElementType.TYPE, ElementType.METHOD })
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Conditional(LinuxCondition.class)
public @interface ConditionalOnLinux {
	// 标注是哪个环境
	String environment() default "";

}
@Configuration
public class ConditionConfig {
        // 只有`@ConditionalOnLinux`的注解属性`environment`是"linux"时才会创建bean
	@Bean
	@ConditionalOnLinux(environment = "linux")
	public Environment linuxEnvironment() {
		return new LinuxEnvironment();
	}
}

上面的代码我们捋一下:

  1. LinuxCondition实现了Condition接口并实现了matches方法,而matches方法则判断@ConditionalOnLinux的注解属性environment是否"linux",是则返回true,否则false。
  2. 然后我们再定义了一个注解@ConditionalOnLinux,这个注解是@Conditional的派生注解,与@Conditional(LinuxCondition.class)等价,注意@ConditionalOnLinux注解定义了一个属性environment。而我们最终可以利用LinuxConditionmatches方法中的参数AnnotatedTypeMetadata来获取@ConditionalOnLinux的注解属性environment的值,从而用来判断值是否为linux"。
  3. 最后我们又定义了一个配置类ConditionConfig,在linuxEnvironment方法上标注了@ConditionalOnLinux(environment = "linux")。因此,这里只有 LinuxConditionmatches方法返回true才会创建bean

学会了如何自定义@ConditionalOnXXX注解后,我们现在再来看下Condition接口的源码:

@FunctionalInterface
public interface Condition {
	boolean matches(ConditionContext context, AnnotatedTypeMetadata metadata);
}

Condition接口主要有一个matches方法,该方法决定了是否要注册相应的bean对象。其中matches方法中有两个参数,参数类型分别是ConditionContextAnnotatedTypeMetadata,这两个参数非常重要。它们分别用来获取一些环境信息和注解元数据从而用在matches方法中判断是否符合条件。

ConditionContext,顾名思义,主要是跟Condition的上下文有关,主要用来获取Registry,BeanFactory,Environment,ResourceLoaderClassLoader等。那么获取这些用来干什么呢?举个栗子,比如OnResourceCondition需要靠ConditionContext来获取ResourceLoader来加载指定资源,OnClassCondition需要靠ConditionContext来获取ClassLoader来加载指定类等,下面看下其源码

public interface ConditionContext {
    BeanDefinitionRegistry getRegistry();
    @Nullable
    ConfigurableListableBeanFactory getBeanFactory();
    Environment getEnvironment();
    ResourceLoader getResourceLoader();
    @Nullable
    ClassLoader getClassLoader();
}

AnnotatedTypeMetadata,这个跟注解元数据有关,利用AnnotatedTypeMetadata可以拿到某个注解的一些元数据,而这些元数据就包含了某个注解里面的属性,比如前面的栗子,利用AnnotatedTypeMetadata可以拿到@ConditionalOnLinux的注解属性environment的值。下面看下其源码:

public interface AnnotatedTypeMetadata {
	boolean isAnnotated(String annotationName);
	Map<String, Object> getAnnotationAttributes(String annotationName);
	Map<String, Object> getAnnotationAttributes(String annotationName, boolean classValuesAsString);
	MultiValueMap<String, Object> getAllAnnotationAttributes(String annotationName);
	MultiValueMap<String, Object> getAllAnnotationAttributes(String annotationName, boolean classValuesAsString);
}

回到刚才的栗子,我们知道@ConditionalOnLinux注解真正起作用的是Condition接口的具体实现类LinuxConditionmatches方法,那么这个matches方法是在何时被调用的呢?

通过idea调试看调用的栈帧,如下图:

发现是在ConditionEvaluatorshouldSkip方法中调用了LinuxConditionmatches方法,自然我们再去看看ConditionEvaluatorshouldSkip的方法执行了什么逻辑。

// 这个方法主要是如果是解析阶段则跳过,如果是注册阶段则不跳过
public boolean shouldSkip(@Nullable AnnotatedTypeMetadata metadata, @Nullable ConfigurationPhase phase) {
	// 若没有被@Conditional或其派生注解所标注,则不会跳过
	if (metadata == null || !metadata.isAnnotated(Conditional.class.getName())) {
		return false;
	}
	// 没有指定phase,注意phase可以分为PARSE_CONFIGURATION或REGISTER_BEAN类型
	if (phase == null) {
		// 若标有@Component,@Import,@Bean或@Configuration等注解的话,则说明是PARSE_CONFIGURATION类型
		if (metadata instanceof AnnotationMetadata &&
				ConfigurationClassUtils.isConfigurationCandidate((AnnotationMetadata) metadata)) {
			return shouldSkip(metadata, ConfigurationPhase.PARSE_CONFIGURATION);
		}
		// 否则是REGISTER_BEAN类型
		return shouldSkip(metadata, ConfigurationPhase.REGISTER_BEAN);
	}

	List<Condition> conditions = new ArrayList<>();
	// TODO 获得所有标有@Conditional注解或其派生注解里面的Condition接口实现类并实例化成对象。
	// 比如@Conditional(OnBeanCondition.class)则获得OnBeanCondition.class,OnBeanCondition.class往往实现了Condition接口
	for (String[] conditionClasses : getConditionClasses(metadata)) {
		// 将类实例化成对象
		for (String conditionClass : conditionClasses) {
			Condition condition = getCondition(conditionClass, this.context.getClassLoader());
			conditions.add(condition);
		}
	}
	// 排序,即按照Condition的优先级进行排序
	AnnotationAwareOrderComparator.sort(conditions);

	for (Condition condition : conditions) {
		ConfigurationPhase requiredPhase = null;
		if (condition instanceof ConfigurationCondition) {
			// 从condition中获得对bean是解析还是注册
			requiredPhase = ((ConfigurationCondition) condition).getConfigurationPhase();
		}
		// 若requiredPhase为null或获取的阶段类型正是当前阶段类型且不符合condition的matches条件,则跳过
		if ((requiredPhase == null || requiredPhase == phase) && !condition.matches(this.context, metadata)) {
			return true;
		}
	}

	return false;
}

shouldSkip这个方法执行的逻辑主要是如果是解析阶段则跳过,如果是注册阶段则不跳过;如果是在注册阶段即REGISTER_BEAN阶段的话,此时会得到所有的Condition接口的具体实现类并实例化这些实现类,然后再执行下面关键的代码进行判断是否需要跳过。

if ((requiredPhase == null || requiredPhase == phase) && !condition.matches(this.context, metadata)) {
    return true;
}

上面代码最重要的逻辑是调用了Condition接口的具体实现类的matches方法,若matches返回false,则跳过,不进行注册bean的操作;若matches返回true,则不跳过,进行注册bean的操作;

好了,Condition的源码分析就到此为止,再往上翻调用方法的话应该就是Spring加载bean定义的相关源码了,不属于这里的分析范围。

SpringBootCondition源码解析

SpringBoot则内置了大量的条件注解ConditionalOnXXX。在分析前,我们先来看一下SpringBootCondition的整体类图来个整体的理解,如下图:

可以看到SpringBootCondition作为SpringBoot条件注解的基类,处于整个类图的中心,它实现了Condition接口,然后又有很多具体的子类OnXXXCondition,这些OnXXXCondition其实就是@ConditionalOnXXX的条件类。

我们先来看下SpringBootCondition这个父类是主要做了哪些事情,抽象了哪些共有的逻辑?

SpringBootConditon实现了Condition接口,作为SpringBoot众多条件注解OnXXXCondtion的父类,它的作用主要就是打印一些条件注解评估报告的日志,比如打印哪些配置类是符合条件注解的,哪些是不符合的。打印的日志形式如下图:

因为SpringBootConditon实现了Condition接口,也实现了matches方法,因此该方法同样也是被ConditionEvaluatorshouldSkip方法中调用,因此我们就以SpringBootConditonmatches方法为入口去进行分析。直接上代码:

// SpringBootCondition.java

public final boolean matches(ConditionContext context,
			AnnotatedTypeMetadata metadata) {
		// 得到metadata的类名或方法名
		String classOrMethodName = getClassOrMethodName(metadata);
		try {
			// 判断每个配置类的每个条件注解@ConditionalOnXXX是否满足条件,然后记录到ConditionOutcome结果中
			// 注意getMatchOutcome是一个抽象模板方法,交给OnXXXCondition子类去实现
			ConditionOutcome outcome = getMatchOutcome(context, metadata);
			// 打印condition评估的日志,哪些条件注解@ConditionalOnXXX是满足条件的,哪些是不满足条件的,这些日志都打印出来
			logOutcome(classOrMethodName, outcome);
			// 除了打印日志外,这些是否匹配的信息还要记录到ConditionEvaluationReport中
			recordEvaluation(context, classOrMethodName, outcome);
			// 最后返回@ConditionalOnXXX是否满足条件
			return outcome.isMatch();
		}
		catch (NoClassDefFoundError ex) {
			throw new IllegalStateException(
					"Could not evaluate condition on " + classOrMethodName + " due to "
							+ ex.getMessage() + " not "
							+ "found. Make sure your own configuration does not rely on "
							+ "that class. This can also happen if you are "
							+ "@ComponentScanning a springframework package (e.g. if you "
							+ "put a @ComponentScan in the default package by mistake)",
					ex);
		}
		catch (RuntimeException ex) {
			throw new IllegalStateException(
					"Error processing condition on " + getName(metadata), ex);
		}
	}

上面代码的注释已经非常详细,我们知道了SpringBootCondition抽象了所有其具体实现类OnXXXCondition的共有逻辑–condition评估信息打印,最重要的是封装了一个模板方法getMatchOutcome(context, metadata),留给各个OnXXXCondition具体子类去覆盖实现属于自己的判断逻辑,然后再返回相应的匹配结果给SpringBootCondition用于日志打印。

因此我们知道了SpringBootCondition其实就是用来打印condition评估信息的,对于其他枝节方法我们不必追究过深,免得丢了主线。我们现在的重点是放在交给OnXXXCondition子类实现的模板方法上getMatchOutcome(context, metadata);

OnBeanCondition源码分析

OnBeanCondition同样继承了FilteringSpringBootCondition父类,覆盖了父类FilteringSpringBootConditiongetOutcomes方法。而FilteringSpringBootCondition又是SpringBootCondition的子类,FilteringSpringBootCondition跟自动配置类过滤有关,这里先不分析。值得注意的是OnBeanCondition同样重写了SpringBootCondition的getMatchOutcome方法,用来判断Spring容器中是否存在指定条件的bean。同时是OnBeanCondition@ConditionalOnBean,@ConditionalOnSingleCandidateConditionalOnMissingBean的条件类。

同样,先来看OnBeanCondition复写父类SpringBootConditiongetMatchOutcome方法的代码:

@Override
	public ConditionOutcome getMatchOutcome(ConditionContext context,
			AnnotatedTypeMetadata metadata) {
		ConditionMessage matchMessage = ConditionMessage.empty();
		// (1),配置类(metadata)标注@ConditionalOnBean注解的情况
		if (metadata.isAnnotated(ConditionalOnBean.class.getName())) {
			// 将@ConditionalOnBean注解属性封装进BeanSearchSpec对象中
			// 注意BeanSearchSpec是一个静态内部类,用来存储@ConditionalOnBean和@ConditionalOnMissingBean注解的属性值
			BeanSearchSpec spec = new BeanSearchSpec(context, metadata,
					ConditionalOnBean.class);
			// 调用getMatchingBeans得到符合条件的bean
			MatchResult matchResult = getMatchingBeans(context, spec);
			// 如果不匹配
			if (!matchResult.isAllMatched()) {
				String reason = createOnBeanNoMatchReason(matchResult);
				return ConditionOutcome.noMatch(ConditionMessage
						.forCondition(ConditionalOnBean.class, spec).because(reason));
			}
			// 如果匹配
			matchMessage = matchMessage.andCondition(ConditionalOnBean.class, spec)
					.found("bean", "beans")
					.items(Style.QUOTE, matchResult.getNamesOfAllMatches());
		}
		// (2),配置类(metadata)标注@ConditionalOnSingleCandidate注解的情况
		if (metadata.isAnnotated(ConditionalOnSingleCandidate.class.getName())) {
			BeanSearchSpec spec = new SingleCandidateBeanSearchSpec(context, metadata,
					ConditionalOnSingleCandidate.class);
			MatchResult matchResult = getMatchingBeans(context, spec);
			if (!matchResult.isAllMatched()) {
				return ConditionOutcome.noMatch(ConditionMessage
						.forCondition(ConditionalOnSingleCandidate.class, spec)
						.didNotFind("any beans").atAll());
			}
			else if (!hasSingleAutowireCandidate(context.getBeanFactory(),
					matchResult.getNamesOfAllMatches(),
					spec.getStrategy() == SearchStrategy.ALL)) {
				return ConditionOutcome.noMatch(ConditionMessage
						.forCondition(ConditionalOnSingleCandidate.class, spec)
						.didNotFind("a primary bean from beans")
						.items(Style.QUOTE, matchResult.getNamesOfAllMatches()));
			}
			matchMessage = matchMessage
					.andCondition(ConditionalOnSingleCandidate.class, spec)
					.found("a primary bean from beans")
					.items(Style.QUOTE, matchResult.getNamesOfAllMatches());
		}
		// (3),配置类(metadata)标注@ConditionalOnMissingBean注解的情况
		if (metadata.isAnnotated(ConditionalOnMissingBean.class.getName())) {
			BeanSearchSpec spec = new BeanSearchSpec(context, metadata,
					ConditionalOnMissingBean.class);
			MatchResult matchResult = getMatchingBeans(context, spec);
			if (matchResult.isAnyMatched()) {
				String reason = createOnMissingBeanNoMatchReason(matchResult);
				return ConditionOutcome.noMatch(ConditionMessage
						.forCondition(ConditionalOnMissingBean.class, spec)
						.because(reason));
			}
			matchMessage = matchMessage.andCondition(ConditionalOnMissingBean.class, spec)
					.didNotFind("any beans").atAll();
		}
		// 最终返回matchMessage
		return ConditionOutcome.match(matchMessage);
	}

步骤

  1. 将该注解属性提取出来封装进BeanSearchSpec对象中;
  2. 然后调用getMatchingBeans(context, spec)方法来获取是否有匹配的bean
  3. 最后返回bean的匹配情况;

看看第二步

protected final MatchResult getMatchingBeans(ConditionContext context,
			BeanSearchSpec beans) {
		// 获得Spring容器的beanFactory
		ConfigurableListableBeanFactory beanFactory = context.getBeanFactory();
		// 判断bean的搜索策略是否是SearchStrategy.ANCESTORS策略
		if (beans.getStrategy() == SearchStrategy.ANCESTORS) {
			BeanFactory parent = beanFactory.getParentBeanFactory();
			Assert.isInstanceOf(ConfigurableListableBeanFactory.class, parent,
					"Unable to use SearchStrategy.PARENTS");
			beanFactory = (ConfigurableListableBeanFactory) parent;
		}
		// MatchResult用来存储bean的匹配结果
		MatchResult matchResult = new MatchResult();
		// 如果bean的搜索策略不是SearchStrategy.CURRENT的话,则置considerHierarchy为true
		boolean considerHierarchy = beans.getStrategy() != SearchStrategy.CURRENT;
		// 获取TypeExtractor,TypeExtractor是用来判断bean的类型的
		TypeExtractor typeExtractor = beans.getTypeExtractor(context.getClassLoader());
		// 获取是否有被忽略bean类型,若有的话将该bean类型的名称装进beansIgnoredByType集合
		// 这里主要是针对@ConditionalOnMissingBean的ignored属性
		List<String> beansIgnoredByType = getNamesOfBeansIgnoredByType(
				beans.getIgnoredTypes(), typeExtractor, beanFactory, context,
				considerHierarchy);
		// 遍历bean的所有类型
		for (String type : beans.getTypes()) {
			// 调用getBeanNamesForType方法根据bean类型得到所有符合条件的bean类型,并放到typeMatches集合
			Collection<String> typeMatches = getBeanNamesForType(beanFactory, type,
					typeExtractor, context.getClassLoader(), considerHierarchy);
			// 移除掉Ignored的类型
			typeMatches.removeAll(beansIgnoredByType);
			// 若typeMatches为空,那么则说明正在遍历的这个type类型不符合匹配条件,此时用matchResult记录一下这个不符合条件的类型
			if (typeMatches.isEmpty()) {
				matchResult.recordUnmatchedType(type);
			}
			// 若typeMatches不为空,那么则说明正在遍历的这个type类型符合匹配条件,此时用matchResult记录一下这个符合条件的类型
			else {
				matchResult.recordMatchedType(type, typeMatches);
			}
		}
		// 这里针对@ConditionalOnBean等注解的annotation属性的处理
		for (String annotation : beans.getAnnotations()) {
			List<String> annotationMatches = Arrays
					.asList(getBeanNamesForAnnotation(beanFactory, annotation,
							context.getClassLoader(), considerHierarchy));
			annotationMatches.removeAll(beansIgnoredByType);
			if (annotationMatches.isEmpty()) {
				matchResult.recordUnmatchedAnnotation(annotation);
			}
			else {
				matchResult.recordMatchedAnnotation(annotation, annotationMatches);
			}
		}
		// 这里针对@ConditionalOnBean等注解的name属性的处理
		for (String beanName : beans.getNames()) {
			// beansIgnoredByType集合不包含beanName且beanFactory包含这个bean,则匹配
			if (!beansIgnoredByType.contains(beanName)
					&& containsBean(beanFactory, beanName, considerHierarchy)) {
				matchResult.recordMatchedName(beanName);
			}
			// 否则,不匹配
			else {
				matchResult.recordUnmatchedName(beanName);
			}
		}
		// 最后返回匹配结果
		return matchResult;
	}

上面的逻辑主要是从spring容器中搜索有无指定条件的bean,搜索Spring容器搜索bean的话有三种搜索策略,分别是CURRENT,ANCESTORSALL,分表表示只从当前的context中搜索bean,只从父context中搜索bean和从整个context中搜索bean;定义了搜索策略后,然后再根据BeanSearchSpec对象封装的注解属性分别取指定的容器中查找有无符合条件的bean,然后再进行一些过滤。比如@ConditionalOnMissingBean注解有定义ignored属性值,那么从容器中搜索到有符合条件的bean时,此时还要移除掉ignored指定的bean

来源

https://juejin.im/post/5e591f6ef265da576b566951

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值