当前位置: 首页 > news >正文

镇江做网站保定网站建设报价

镇江做网站,保定网站建设报价,浙江省建设厅证书查询,没有做老千的斗牛网站📖摘要 今天分享下 —— SpringBoot系列:SpringBoot中的条件注解是如何实现的 的一些基本知识,欢迎关注! 🌂分享 SpringBoot 内部提供了特有的注解:条件注解(Conditional Annotation)。比如: …

📖摘要


今天分享下 —— SpringBoot系列:SpringBoot中的条件注解是如何实现的 的一些基本知识,欢迎关注!


🌂分享

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

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

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

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

@Configuration
@ConditionalOnClass({ freemarker.template.Configuration.class,FreeMarkerConfigurationFactory.class })
@AutoConfigureAfter(WebMvcAutoConfiguration.class)
@EnableConfigurationProperties(FreeMarkerProperties.class)
public class FreeMarkerAutoConfiguration

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


✌条件注解内部的一些基础

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

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

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

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

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

Condition接口有个子接口ConfigurationCondition:

public interface ConfigurationCondition extends Condition {ConfigurationPhase getConfigurationPhase();public static enum ConfigurationPhase {PARSE_CONFIGURATION,REGISTER_BEAN}
}

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

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

@Override
public final boolean matches(ConditionContext context,AnnotatedTypeMetadata metadata) {String classOrMethodName = getClassOrMethodName(metadata); // 得到类名或者方法名(条件注解可以作用的类或者方法上)try {ConditionOutcome outcome = getMatchOutcome(context, metadata); // 抽象方法,具体子类实现。ConditionOutcome记录了匹配结果boolean和log信息logOutcome(classOrMethodName, outcome); // log记录一下匹配信息recordEvaluation(context, classOrMethodName, outcome); // 报告记录一下匹配信息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);}
}

🤞基于Class的条件注解

SpringBoot提供了两个基于Class的条件注解:

  • @ConditionalOnClass(类加载器中存在指明的类)或者@ConditionalOnMissingClass(类加载器中不存在指明的类)。
  • @ConditionalOnClass或者@ConditionalOnMissingClass注解对应的条件类是OnClassCondition,定义如下:
@Order(Ordered.HIGHEST_PRECEDENCE) // 优先级、最高级别
class OnClassCondition extends SpringBootCondition {@Overridepublic ConditionOutcome getMatchOutcome(ConditionContext context,AnnotatedTypeMetadata metadata) {StringBuffer matchMessage = new StringBuffer(); // 记录匹配信息MultiValueMap<String, Object> onClasses = getAttributes(metadata,ConditionalOnClass.class); // 得到@ConditionalOnClass注解的属性if (onClasses != null) { // 如果属性存在List<String> missing = getMatchingClasses(onClasses, MatchType.MISSING,context); // 得到在类加载器中不存在的类if (!missing.isEmpty()) { // 如果存在类加载器中不存在对应的类,返回一个匹配失败的ConditionalOutcomereturn ConditionOutcome.noMatch("required @ConditionalOnClass classes not found: "+ StringUtils.collectionToCommaDelimitedString(missing));}// 如果类加载器中存在对应的类的话,匹配信息进行记录matchMessage.append("@ConditionalOnClass classes found: "+ StringUtils.collectionToCommaDelimitedString(getMatchingClasses(onClasses, MatchType.PRESENT, context)));}// 对@ConditionalOnMissingClass注解做相同的逻辑处理(说明@ConditionalOnClass和@ConditionalOnMissingClass可以一起使用)MultiValueMap<String, Object> onMissingClasses = getAttributes(metadata,ConditionalOnMissingClass.class);if (onMissingClasses != null) {List<String> present = getMatchingClasses(onMissingClasses, MatchType.PRESENT,context);if (!present.isEmpty()) {return ConditionOutcome.noMatch("required @ConditionalOnMissing classes found: "+ StringUtils.collectionToCommaDelimitedString(present));}matchMessage.append(matchMessage.length() == 0 ? "" : " ");matchMessage.append("@ConditionalOnMissing classes not found: "+ StringUtils.collectionToCommaDelimitedString(getMatchingClasses(onMissingClasses, MatchType.MISSING, context)));}// 返回全部匹配成功的ConditionalOutcomereturn ConditionOutcome.match(matchMessage.toString());}private enum MatchType { // 枚举:匹配类型。用于查询类名在对应的类加载器中是否存在。PRESENT { // 匹配成功@Overridepublic boolean matches(String className, ConditionContext context) {return ClassUtils.isPresent(className, context.getClassLoader());}},MISSING { // 匹配不成功@Overridepublic boolean matches(String className, ConditionContext context) {return !ClassUtils.isPresent(className, context.getClassLoader());}};public abstract boolean matches(String className, ConditionContext context);}}

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

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

🙌基于Bean的条件注解

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

@ConditionOnBean 注解定义如下:

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

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

@Override
public ConditionOutcome getMatchOutcome(ConditionContext context,AnnotatedTypeMetadata metadata) {StringBuffer matchMessage = new StringBuffer(); // 记录匹配信息if (metadata.isAnnotated(ConditionalOnBean.class.getName())) {BeanSearchSpec spec = new BeanSearchSpec(context, metadata,ConditionalOnBean.class); // 构造一个BeanSearchSpec,会从@ConditionalOnBean注解中获取属性,然后设置到BeanSearchSpec中List<String> matching = getMatchingBeans(context, spec); // 从BeanFactory中根据策略找出所有匹配的beanif (matching.isEmpty()) { // 如果没有匹配的bean,返回一个没有匹配成功的ConditionalOutcomereturn ConditionOutcome.noMatch("@ConditionalOnBean " + spec + " found no beans");}// 如果找到匹配的bean,匹配信息进行记录matchMessage.append("@ConditionalOnBean " + spec + " found the following " + matching);}if (metadata.isAnnotated(ConditionalOnSingleCandidate.class.getName())) { // 相同的逻辑,针对@ConditionalOnSingleCandidate注解BeanSearchSpec spec = new SingleCandidateBeanSearchSpec(context, metadata,ConditionalOnSingleCandidate.class);List<String> matching = getMatchingBeans(context, spec);if (matching.isEmpty()) {return ConditionOutcome.noMatch("@ConditionalOnSingleCandidate " + spec + " found no beans");}else if (!hasSingleAutowireCandidate(context.getBeanFactory(), matching)) { // 多了一层判断,判断是否只有一个beanreturn ConditionOutcome.noMatch("@ConditionalOnSingleCandidate " + spec+ " found no primary candidate amongst the" + " following "+ matching);}matchMessage.append("@ConditionalOnSingleCandidate " + spec + " found "+ "a primary candidate amongst the following " + matching);}if (metadata.isAnnotated(ConditionalOnMissingBean.class.getName())) { // 相同的逻辑,针对@ConditionalOnMissingBean注解BeanSearchSpec spec = new BeanSearchSpec(context, metadata,ConditionalOnMissingBean.class);List<String> matching = getMatchingBeans(context, spec);if (!matching.isEmpty()) {return ConditionOutcome.noMatch("@ConditionalOnMissingBean " + spec+ " found the following " + matching);}matchMessage.append(matchMessage.length() == 0 ? "" : " ");matchMessage.append("@ConditionalOnMissingBean " + spec + " found no beans");}return ConditionOutcome.match(matchMessage.toString()); //返回匹配成功的ConditonalOutcome
}

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


👍各种条件注解的总结

在这里插入图片描述
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述


👌SpringBoot条件注解的激活机制

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

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

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

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

public ConfigurationClassParser(MetadataReaderFactory metadataReaderFactory,ProblemReporter problemReporter, Environment environment, ResourceLoader resourceLoader,BeanNameGenerator componentScanBeanNameGenerator, BeanDefinitionRegistry registry) {this.metadataReaderFactory = metadataReaderFactory;this.problemReporter = problemReporter;this.environment = environment;this.resourceLoader = resourceLoader;this.registry = registry;this.componentScanParser = new ComponentScanAnnotationParser(resourceLoader, environment, componentScanBeanNameGenerator, registry);// 构造ConditionEvaluator用于处理条件注解this.conditionEvaluator = new ConditionEvaluator(registry, environment, resourceLoader);
}ConfigurationClassParser对每个配置类进行解析的时候都会使用ConditionEvaluator:if (this.conditionEvaluator.shouldSkip(configClass.getMetadata(), ConfigurationPhase.PARSE_CONFIGURATION)) {return;
}

ConditionEvaluatorskip 方法:

public boolean shouldSkip(AnnotatedTypeMetadata metadata, ConfigurationPhase phase) {// 如果这个类没有被@Conditional注解所修饰,不会skipif (metadata == null || !metadata.isAnnotated(Conditional.class.getName())) {return false;}// 如果参数中沒有设置条件注解的生效阶段if (phase == null) {// 是配置类的话直接使用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<Condition>();// 获取配置类的条件注解得到条件数据,并添加到集合中for (String[] conditionClasses : getConditionClasses(metadata)) {for (String conditionClass : conditionClasses) {Condition condition = getCondition(conditionClass, this.context.getClassLoader());conditions.add(condition);}}// 对条件集合做个排序AnnotationAwareOrderComparator.sort(conditions);// 遍历条件集合for (Condition condition : conditions) {ConfigurationPhase requiredPhase = null;if (condition instanceof ConfigurationCondition) {requiredPhase = ((ConfigurationCondition) condition).getConfigurationPhase();}// 没有这个解析类不需要阶段的判断或者解析类和参数中的阶段一致才会继续进行if (requiredPhase == null || requiredPhase == phase) {// 阶段一致切不满足条件的话,返回true并跳过这个bean的解析if (!condition.matches(this.context, metadata)) {return true;}}}return false;
}

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

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

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

.......
org.springframework.boot.autoconfigure.freemarker.FreeMarkerAutoConfiguration -- OnClassCondition -- required @ConditionalOnClass classes not found: freemarker.template.Configuration,org.springframework.ui.freemarker.FreeMarkerConfigurationFactory
org.springframework.boot.autoconfigure.groovy.template.GroovyTemplateAutoConfiguration -- OnClassCondition -- required @ConditionalOnClass classes not found: groovy.text.markup.MarkupTemplateEngine
org.springframework.boot.autoconfigure.gson.GsonAutoConfiguration -- OnClassCondition -- required @ConditionalOnClass classes not found: com.google.gson.Gson
org.springframework.boot.autoconfigure.h2.H2ConsoleAutoConfiguration -- OnClassCondition -- required @ConditionalOnClass classes not found: org.h2.server.web.WebServlet
org.springframework.boot.autoconfigure.hateoas.HypermediaAutoConfiguration -- OnClassCondition -- required @ConditionalOnClass classes not found: org.springframework.hateoas.Resource,org.springframework.plugin.core.Plugin
org.springframework.boot.autoconfigure.hazelcast.HazelcastAutoConfiguration -- OnClassCondition -- required @ConditionalOnClass classes not found: com.hazelcast.core.HazelcastInstance
.......

🎉最后

  • 更多参考精彩博文请看这里:《陈永佳的博客》

  • 喜欢博主的小伙伴可以加个关注、点个赞哦,持续更新嘿嘿!

http://www.lbrq.cn/news/2487367.html

相关文章:

  • 可以做网站的编程有什么百度一下一下你就知道
  • 中国建设银行积分商城网站网络营销的主要方法
  • 湖南网站建设kaodezhu广告关键词有哪些类型
  • 网站开发的工作内容万网官网域名注册
  • 给个网址2021年能看的seo体系百科
  • 商城网站建设定制网站建设培训网站官网
  • 厦门市建设管理协会网站首页什么是营销
  • 男女做那个的免费视频网站我是新手如何做电商
  • 各地平台网站手机百度引擎搜索入口
  • 青岛网站建设方案书seo优化推广
  • 北京餐饮培训网站建设南京市网站
  • 北京网站建设方案书做做网站
  • 晋中路桥建设集团网站网站seo顾问
  • 杭州做公司网站哪家好电商数据分析
  • ps简单网页设计模板图片广州品牌seo推广
  • 零陵做网站seoheuni
  • 什么样的网站需要备案seo模拟点击有用吗
  • 怎么做应援网站百度品牌专区
  • 包包网站建设什么是搜索引擎营销?
  • 做网站时量宽度的尺子工具适合seo优化的网站
  • 百度商桥怎么接网站营销策略包括哪些内容
  • 中山市建设局网站产品营销策划方案3000字
  • 自己做的网站为什么访问不互联网广告平台代理
  • 专做立体化的网站谷歌seo一个月费用需要2万吗
  • 建网站权威公司百度问答
  • 网页的网站建设在哪里营销策划与运营公司
  • 哪些网站专门做动漫的深圳知名seo公司
  • 品牌网站建设推广智能建站模板
  • 百度收录网站名字大连网络营销seo
  • 做国外销售都上什么网站启动互联全网营销推广
  • 设备独立性软件-高速缓存与缓冲区
  • k8s pod生命周期、初始化容器、钩子函数、容器探测、重启策略
  • 逆向入门(43)程序逆向篇-tsrh-crackme
  • Java面试精进:测试、监控与序列化技术全解析
  • Jenkins运行pytest时指令失效的原因以及解决办法
  • HTML5元素相关补充