面试:SpringBoot中的条件注解底层是如何实现的?

末蓝、 2023-03-03 11:12 80阅读 0赞

点击上方“java大数据修炼之道”,选择“置顶或者星标”

你想要的优质技术好文第一时间送达!

format_png

来源 | https://urlify.cn/bm2qqi

SpringBoot内部提供了特有的注解:条件注解(Conditional Annotation)。比如:

  • @ConditionalOnBean、
  • @ConditionalOnClass、
  • @ConditionalOnExpression、
  • @ConditionalOnMissingBean等。

条件注解存在的意义在于动态识别(也可以说是代码自动化执行)。比如@ConditionalOnClass会检查类加载器中是否存在对应的类,如果有的话被注解修饰的类就有资格被Spring容器所注册,否则会被skip。

比如FreemarkerAutoConfiguration这个自动化配置类的定义如下:

  1. @Configuration
  2. @ConditionalOnClass({ freemarker.template.Configuration.class,
  3. FreeMarkerConfigurationFactory.class })
  4. @AutoConfigureAfter(WebMvcAutoConfiguration.class)
  5. @EnableConfigurationProperties(FreeMarkerProperties.class)
  6. public class FreeMarkerAutoConfiguration

这个自动化配置类被@ConditionalOnClass条件注解修饰,这个条件注解存在的意义在于判断类加载器中是否存在freemarker.template.Configuration和FreeMarkerConfigurationFactory这两个类,如果都存在的话会在Spring容器中加载这个FreeMarkerAutoConfiguration配置类;否则不会加载。

条件注解内部的一些基础

在分析条件注解的底层实现之前,我们先来看一下这些条件注解的定义。以@ConditionalOnClass注解为例,它的定义如下:

  1. @Target({ ElementType.TYPE, ElementType.METHOD })
  2. @Retention(RetentionPolicy.RUNTIME)
  3. @Documented
  4. @Conditional(OnClassCondition.class)
  5. public @interface ConditionalOnClass {
  6. Class<?>[] value() default {}; // 需要匹配的类
  7. String[] name() default {}; // 需要匹配的类名
  8. }

它有2个属性,分别是类数组和字符串数组(作用一样,类型不一样),而且被@Conditional注解所修饰,这个@Conditional注解有个名为values的Class<? extends Condition>[]类型的属性。这个Condition是个接口,用于匹配组件是否有资格被容器注册,定义如下:

  1. public interface Condition {
  2. // ConditionContext内部会存储Spring容器、应用程序环境信息、资源加载器、类加载器
  3. boolean matches(ConditionContext context, AnnotatedTypeMetadata metadata);
  4. }

也就是说@Conditional注解属性中可以持有多个Condition接口的实现类,所有的Condition接口需要全部匹配成功后这个@Conditional修饰的组件才有资格被注册。

Condition接口有个子接口ConfigurationCondition:

  1. public interface ConfigurationCondition extends Condition {
  2. ConfigurationPhase getConfigurationPhase();
  3. public static enum ConfigurationPhase {
  4. PARSE_CONFIGURATION,
  5. REGISTER_BEAN
  6. }
  7. }

这个子接口是一种特殊的条件接口,多了一个getConfigurationPhase方法,也就是条件注解的生效阶段。只有在ConfigurationPhase中定义的两种阶段下才会生效。

Condition接口有个实现抽象类SpringBootCondition,SpringBoot中所有条件注解对应的条件类都继承这个抽象类。它实现了matches方法:

  1. @Override
  2. public final boolean matches(ConditionContext context,
  3. AnnotatedTypeMetadata metadata) {
  4. String classOrMethodName = getClassOrMethodName(metadata); // 得到类名或者方法名(条件注解可以作用的类或者方法上)
  5. try {
  6. ConditionOutcome outcome = getMatchOutcome(context, metadata); // 抽象方法,具体子类实现。ConditionOutcome记录了匹配结果boolean和log信息
  7. logOutcome(classOrMethodName, outcome); // log记录一下匹配信息
  8. recordEvaluation(context, classOrMethodName, outcome); // 报告记录一下匹配信息
  9. return outcome.isMatch(); // 返回是否匹配
  10. }
  11. catch (NoClassDefFoundError ex) {
  12. throw new IllegalStateException(
  13. "Could not evaluate condition on " + classOrMethodName + " due to "
  14. + ex.getMessage() + " not "
  15. + "found. Make sure your own configuration does not rely on "
  16. + "that class. This can also happen if you are "
  17. + "@ComponentScanning a springframework package (e.g. if you "
  18. + "put a @ComponentScan in the default package by mistake)",
  19. ex);
  20. }
  21. catch (RuntimeException ex) {
  22. throw new IllegalStateException(
  23. "Error processing condition on " + getName(metadata), ex);
  24. }
  25. }

基于Class的条件注解

SpringBoot提供了两个基于Class的条件注解:@ConditionalOnClass(类加载器中存在指明的类)或者@ConditionalOnMissingClass(类加载器中不存在指明的类)。

@ConditionalOnClass或者@ConditionalOnMissingClass注解对应的条件类是OnClassCondition,定义如下:

  1. @Order(Ordered.HIGHEST_PRECEDENCE) // 优先级、最高级别
  2. class OnClassCondition extends SpringBootCondition {
  3. @Override
  4. public ConditionOutcome getMatchOutcome(ConditionContext context,
  5. AnnotatedTypeMetadata metadata) {
  6. StringBuffer matchMessage = new StringBuffer(); // 记录匹配信息
  7. MultiValueMap<String, Object> onClasses = getAttributes(metadata,
  8. ConditionalOnClass.class); // 得到@ConditionalOnClass注解的属性
  9. if (onClasses != null) { // 如果属性存在
  10. List<String> missing = getMatchingClasses(onClasses, MatchType.MISSING,
  11. context); // 得到在类加载器中不存在的类
  12. if (!missing.isEmpty()) { // 如果存在类加载器中不存在对应的类,返回一个匹配失败的ConditionalOutcome
  13. return ConditionOutcome
  14. .noMatch("required @ConditionalOnClass classes not found: "
  15. + StringUtils.collectionToCommaDelimitedString(missing));
  16. }
  17. // 如果类加载器中存在对应的类的话,匹配信息进行记录
  18. matchMessage.append("@ConditionalOnClass classes found: "
  19. + StringUtils.collectionToCommaDelimitedString(
  20. getMatchingClasses(onClasses, MatchType.PRESENT, context)));
  21. }
  22. // 对@ConditionalOnMissingClass注解做相同的逻辑处理(说明@ConditionalOnClass和@ConditionalOnMissingClass可以一起使用)
  23. MultiValueMap<String, Object> onMissingClasses = getAttributes(metadata,
  24. ConditionalOnMissingClass.class);
  25. if (onMissingClasses != null) {
  26. List<String> present = getMatchingClasses(onMissingClasses, MatchType.PRESENT,
  27. context);
  28. if (!present.isEmpty()) {
  29. return ConditionOutcome
  30. .noMatch("required @ConditionalOnMissing classes found: "
  31. + StringUtils.collectionToCommaDelimitedString(present));
  32. }
  33. matchMessage.append(matchMessage.length() == 0 ? "" : " ");
  34. matchMessage.append("@ConditionalOnMissing classes not found: "
  35. + StringUtils.collectionToCommaDelimitedString(getMatchingClasses(
  36. onMissingClasses, MatchType.MISSING, context)));
  37. }
  38. // 返回全部匹配成功的ConditionalOutcome
  39. return ConditionOutcome.match(matchMessage.toString());
  40. }
  41. private enum MatchType { // 枚举:匹配类型。用于查询类名在对应的类加载器中是否存在。
  42. PRESENT { // 匹配成功
  43. @Override
  44. public boolean matches(String className, ConditionContext context) {
  45. return ClassUtils.isPresent(className, context.getClassLoader());
  46. }
  47. },
  48. MISSING { // 匹配不成功
  49. @Override
  50. public boolean matches(String className, ConditionContext context) {
  51. return !ClassUtils.isPresent(className, context.getClassLoader());
  52. }
  53. };
  54. public abstract boolean matches(String className, ConditionContext context);
  55. }
  56. }

比如FreemarkerAutoConfiguration中的@ConditionalOnClass注解中有value属性是freemarker.template.Configuration.class和FreeMarkerConfigurationFactory.class。在OnClassCondition执行过程中得到的最终ConditionalOutcome中的log message如下:

  1. 1 @ConditionalOnClass classes found: freemarker.template.Configuration,org.springframework.ui.freemarker.FreeMarkerConfigurationFactory

基于Bean的条件注解

@ConditionalOnBean(Spring容器中存在指明的bean)、@ConditionalOnMissingBean(Spring容器中不存在指明的bean)以及ConditionalOnSingleCandidate(Spring容器中存在且只存在一个指明的bean)都是基于Bean的条件注解,它们对应的条件类是ConditionOnBean。

@ConditionOnBean注解定义如下:

  1. @Target({ ElementType.TYPE, ElementType.METHOD })
  2. @Retention(RetentionPolicy.RUNTIME)
  3. @Documented
  4. @Conditional(OnBeanCondition.class)
  5. public @interface ConditionalOnBean {
  6. Class<?>[] value() default {}; // 匹配的bean类型
  7. String[] type() default {}; // 匹配的bean类型的类名
  8. Class<? extends Annotation>[] annotation() default {}; // 匹配的bean注解
  9. String[] name() default {}; // 匹配的bean的名字
  10. SearchStrategy search() default SearchStrategy.ALL; // 搜索策略。提供CURRENT(只在当前容器中找)、PARENTS(只在所有的父容器中找;但是不包括当前容器)和ALL(CURRENT和PARENTS的组合)
  11. }

OnBeanCondition条件类的匹配代码如下:

  1. @Override
  2. public ConditionOutcome getMatchOutcome(ConditionContext context,
  3. AnnotatedTypeMetadata metadata) {
  4. StringBuffer matchMessage = new StringBuffer(); // 记录匹配信息
  5. if (metadata.isAnnotated(ConditionalOnBean.class.getName())) {
  6. BeanSearchSpec spec = new BeanSearchSpec(context, metadata,
  7. ConditionalOnBean.class); // 构造一个BeanSearchSpec,会从@ConditionalOnBean注解中获取属性,然后设置到BeanSearchSpec中
  8. List<String> matching = getMatchingBeans(context, spec); // 从BeanFactory中根据策略找出所有匹配的bean
  9. if (matching.isEmpty()) { // 如果没有匹配的bean,返回一个没有匹配成功的ConditionalOutcome
  10. return ConditionOutcome
  11. .noMatch("@ConditionalOnBean " + spec + " found no beans");
  12. }
  13. // 如果找到匹配的bean,匹配信息进行记录
  14. matchMessage.append(
  15. "@ConditionalOnBean " + spec + " found the following " + matching);
  16. }
  17. if (metadata.isAnnotated(ConditionalOnSingleCandidate.class.getName())) { // 相同的逻辑,针对@ConditionalOnSingleCandidate注解
  18. BeanSearchSpec spec = new SingleCandidateBeanSearchSpec(context, metadata,
  19. ConditionalOnSingleCandidate.class);
  20. List<String> matching = getMatchingBeans(context, spec);
  21. if (matching.isEmpty()) {
  22. return ConditionOutcome.noMatch(
  23. "@ConditionalOnSingleCandidate " + spec + " found no beans");
  24. }
  25. else if (!hasSingleAutowireCandidate(context.getBeanFactory(), matching)) { // 多了一层判断,判断是否只有一个bean
  26. return ConditionOutcome.noMatch("@ConditionalOnSingleCandidate " + spec
  27. + " found no primary candidate amongst the" + " following "
  28. + matching);
  29. }
  30. matchMessage.append("@ConditionalOnSingleCandidate " + spec + " found "
  31. + "a primary candidate amongst the following " + matching);
  32. }
  33. if (metadata.isAnnotated(ConditionalOnMissingBean.class.getName())) { // 相同的逻辑,针对@ConditionalOnMissingBean注解
  34. BeanSearchSpec spec = new BeanSearchSpec(context, metadata,
  35. ConditionalOnMissingBean.class);
  36. List<String> matching = getMatchingBeans(context, spec);
  37. if (!matching.isEmpty()) {
  38. return ConditionOutcome.noMatch("@ConditionalOnMissingBean " + spec
  39. + " found the following " + matching);
  40. }
  41. matchMessage.append(matchMessage.length() == 0 ? "" : " ");
  42. matchMessage.append("@ConditionalOnMissingBean " + spec + " found no beans");
  43. }
  44. return ConditionOutcome.match(matchMessage.toString()); //返回匹配成功的ConditonalOutcome
  45. }

SpringBoot还提供了其他比如ConditionalOnJava、ConditionalOnNotWebApplication、ConditionalOnWebApplication、ConditionalOnResource、ConditionalOnProperty、ConditionalOnExpression等条件注解,有兴趣的读者可以自行查看它们的底层处理逻辑。

各种条件注解的总结

format_png 1

format_png 2

format_png 3

format_png 4

SpringBoot条件注解的激活机制

分析完了条件注解的执行逻辑之后,接下来的问题就是SpringBoot是如何让这些条件注解生效的?

SpringBoot使用ConditionEvaluator这个内部类完成条件注解的解析和判断。

在Spring容器的refresh过程中,只有跟解析或者注册bean有关系的类都会使用ConditionEvaluator完成条件注解的判断,这个过程中一些类不满足条件的话就会被skip。这些类比如有AnnotatedBeanDefinitionReader、ConfigurationClassBeanDefinitionReader、ConfigurationClassParse、ClassPathScanningCandidateComponentProvider等。

比如ConfigurationClassParser的构造函数会初始化内部属性conditionEvaluator:

  1. public ConfigurationClassParser(MetadataReaderFactory metadataReaderFactory,
  2. ProblemReporter problemReporter, Environment environment, ResourceLoader resourceLoader,
  3. BeanNameGenerator componentScanBeanNameGenerator, BeanDefinitionRegistry registry) {
  4. this.metadataReaderFactory = metadataReaderFactory;
  5. this.problemReporter = problemReporter;
  6. this.environment = environment;
  7. this.resourceLoader = resourceLoader;
  8. this.registry = registry;
  9. this.componentScanParser = new ComponentScanAnnotationParser(
  10. resourceLoader, environment, componentScanBeanNameGenerator, registry);
  11. // 构造ConditionEvaluator用于处理条件注解
  12. this.conditionEvaluator = new ConditionEvaluator(registry, environment, resourceLoader);
  13. }
  14. ConfigurationClassParser对每个配置类进行解析的时候都会使用ConditionEvaluator
  15. if (this.conditionEvaluator.shouldSkip(configClass.getMetadata(), ConfigurationPhase.PARSE_CONFIGURATION)) {
  16. return;
  17. }

ConditionEvaluator的skip方法:

  1. public boolean shouldSkip(AnnotatedTypeMetadata metadata, ConfigurationPhase phase) {
  2. // 如果这个类没有被@Conditional注解所修饰,不会skip
  3. if (metadata == null || !metadata.isAnnotated(Conditional.class.getName())) {
  4. return false;
  5. }
  6. // 如果参数中沒有设置条件注解的生效阶段
  7. if (phase == null) {
  8. // 是配置类的话直接使用PARSE_CONFIGURATION阶段
  9. if (metadata instanceof AnnotationMetadata &&
  10. ConfigurationClassUtils.isConfigurationCandidate((AnnotationMetadata) metadata)) {
  11. return shouldSkip(metadata, ConfigurationPhase.PARSE_CONFIGURATION);
  12. }
  13. // 否则使用REGISTER_BEAN阶段
  14. return shouldSkip(metadata, ConfigurationPhase.REGISTER_BEAN);
  15. }
  16. // 要解析的配置类的条件集合
  17. List<Condition> conditions = new ArrayList<Condition>();
  18. // 获取配置类的条件注解得到条件数据,并添加到集合中
  19. for (String[] conditionClasses : getConditionClasses(metadata)) {
  20. for (String conditionClass : conditionClasses) {
  21. Condition condition = getCondition(conditionClass, this.context.getClassLoader());
  22. conditions.add(condition);
  23. }
  24. }
  25. // 对条件集合做个排序
  26. AnnotationAwareOrderComparator.sort(conditions);
  27. // 遍历条件集合
  28. for (Condition condition : conditions) {
  29. ConfigurationPhase requiredPhase = null;
  30. if (condition instanceof ConfigurationCondition) {
  31. requiredPhase = ((ConfigurationCondition) condition).getConfigurationPhase();
  32. }
  33. // 没有这个解析类不需要阶段的判断或者解析类和参数中的阶段一致才会继续进行
  34. if (requiredPhase == null || requiredPhase == phase) {
  35. // 阶段一致切不满足条件的话,返回true并跳过这个bean的解析
  36. if (!condition.matches(this.context, metadata)) {
  37. return true;
  38. }
  39. }
  40. }
  41. return false;
  42. }

SpringBoot在条件注解的解析log记录在了ConditionEvaluationReport类中,可以通过BeanFactory获取(BeanFactory是有父子关系的;每个BeanFactory都存有一份ConditionEvaluationReport,互不相干):

  1. ConditionEvaluationReport conditionEvaluationReport = beanFactory.getBean("autoConfigurationReport", ConditionEvaluationReport.class);
  2. Map<String, ConditionEvaluationReport.ConditionAndOutcomes> result = conditionEvaluationReport.getConditionAndOutcomesBySource();
  3. for(String key : result.keySet()) {
  4. ConditionEvaluationReport.ConditionAndOutcomes conditionAndOutcomes = result.get(key);
  5. Iterator<ConditionEvaluationReport.ConditionAndOutcome> iterator = conditionAndOutcomes.iterator();
  6. while(iterator.hasNext()) {
  7. ConditionEvaluationReport.ConditionAndOutcome conditionAndOutcome = iterator.next();
  8. System.out.println(key + " -- " + conditionAndOutcome.getCondition().getClass().getSimpleName() + " -- " + conditionAndOutcome.getOutcome());
  9. }
  10. }

打印出条件注解下的类加载信息:

  1. .......
  2. org.springframework.boot.autoconfigure.freemarker.FreeMarkerAutoConfiguration -- OnClassCondition -- required @ConditionalOnClass classes not found: freemarker.template.Configuration,org.springframework.ui.freemarker.FreeMarkerConfigurationFactory
  3. org.springframework.boot.autoconfigure.groovy.template.GroovyTemplateAutoConfiguration -- OnClassCondition -- required @ConditionalOnClass classes not found: groovy.text.markup.MarkupTemplateEngine
  4. org.springframework.boot.autoconfigure.gson.GsonAutoConfiguration -- OnClassCondition -- required @ConditionalOnClass classes not found: com.google.gson.Gson
  5. org.springframework.boot.autoconfigure.h2.H2ConsoleAutoConfiguration -- OnClassCondition -- required @ConditionalOnClass classes not found: org.h2.server.web.WebServlet
  6. org.springframework.boot.autoconfigure.hateoas.HypermediaAutoConfiguration -- OnClassCondition -- required @ConditionalOnClass classes not found: org.springframework.hateoas.Resource,org.springframework.plugin.core.Plugin
  7. org.springframework.boot.autoconfigure.hazelcast.HazelcastAutoConfiguration -- OnClassCondition -- required @ConditionalOnClass classes not found: com.hazelcast.core.HazelcastInstance
  8. .......
  9. 最近热文阅读:1、这21 个刁钻的HashMap 面试题,我把阿里面试官吊打了!
  10. 2Java中:如何把异常设计的更优雅?
  11. 3String 也能做性能优化,我只能说牛逼!
  12. 4、超实用的18Java8日期处理的实践!
  13. 5、微信支付的软件架构也太特么牛逼了吧...!
  14. 6、这12张手绘图,让我彻底搞懂了微服务架构!
  15. 7、别用Date了,Java8新特性之日期处理,现在学会也不迟!
  16. 8Java中当对象不再使用时,不赋值为null会导致什么后果
  17. 9SQL 查询总是先执行SELECT语句吗?你们都错了!
  18. 10、我把SpringBootbanner换成了美女,老板:工作不饱和,建议加班关注 java大数据修炼之道每天学习java技术,你想学的Java知识这里都有!微信扫描二维码,关注我的公众号写留言
  19. 喜欢就给个“在看”

发表评论

表情:
评论列表 (有 0 条评论,80人围观)

还没有评论,来说两句吧...

相关阅读