面試必問: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.Configuration和FreeMarkerConfigurationFactory這兩個類,如果都存在的話會在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註解有個名為values的Class<? 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介面有個實現抽象類SpringBootCondition,SpringBoot中所有條件註解對應的條件類都繼承這個抽象類。它實現了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 { @Override public 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()) { // 如果存在類載入器中不存在對應的類,返回一個匹配失敗的ConditionalOutcome
return 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))); } // 返回全部匹配成功的ConditionalOutcome return ConditionOutcome.match(matchMessage.toString());
} private enum MatchType { // 列舉:匹配型別。用於查詢類名在對應的類載入器中是否存在。
PRESENT { // 匹配成功
@Override public boolean matches(String className, ConditionContext context) { return ClassUtils.isPresent(className, context.getClassLoader());
} }, MISSING { // 匹配不成功
@Override public 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.class和FreeMarkerConfigurationFactory.class。在OnClassCondition執行過程中得到的最終ConditionalOutcome中的log message如下:
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註解定義如下:
@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中根據策略找出所有匹配的bean
if (matching.isEmpty()) { // 如果沒有匹配的bean,返回一個沒有匹配成功的ConditionalOutcome
return 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)) { // 多了一層判斷,判斷是否只有一個bean
return 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;
}
ConditionEvaluator的skip方法:
public boolean shouldSkip(AnnotatedTypeMetadata metadata, ConfigurationPhase phase) {
// 如果這個類沒有被@Conditional註解所修飾,不會skip
if (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
.......
每天進步一點點,Peace!
喜歡可以幫作者點個關注,感謝大家支援!
相關文章
- SpringBoot原始碼分析之條件註解的底層實現Spring Boot原始碼
- 面試必問:HashMap 底層實現原理分析面試HashMap
- 面試官:說說反射的底層實現原理?面試反射
- Golang channel底層是如何實現的?(深度好文)Golang
- 面試題深入解析:Synchronized底層實現面試題synchronized
- 位元組面試:什麼是讀寫分離?讀寫分離的底層如何實現?面試
- synchronized底層是怎麼實現的?synchronized
- 面試官問:為什麼HashMap底層樹化的元素是 8面試HashMap
- 【AQS面試篇】瞭解ReentrantLock嗎?講講其底層實現AQS面試ReentrantLock
- 面試必備之MYSQL索引底層原理分析面試MySql索引
- 面試官: 有了解過ReentrantLock的底層實現嗎?說說看面試ReentrantLock
- LinkedList的底層實現
- 面試大廠才發現,索引都問這些底層知識?更怕的是自己不懂原理!面試索引
- SpringBoot | SpringBoot 是如何實現日誌的?Spring Boot
- 求教測試平臺底層是如何運作的
- 面試必問的volatile,你瞭解多少?面試
- SpringBoot基礎篇Bean之條件注入之註解使用Spring BootBean
- SpringBoot中搭配AOP實現自定義註解Spring Boot
- Laravel 的 CSRF - 白名單底層是怎麼實現的Laravel
- Spring條件註解@ConditionalSpring
- 一文帶你看懂Java中的Lock鎖底層AQS到底是如何實現的JavaAQS
- 詳解 PHP 陣列的底層實現:HashTablePHP陣列
- ArrayList底層的實現原理
- 死磕Synchronized底層實現,面試你還怕什麼?synchronized面試
- 關於Laravel框架中Guard的底層實現Laravel框架
- 【面試普通人VS高手系列】ConcurrentHashMap 底層具體實現知道嗎?實現原理是什麼?面試HashMap
- 深入底層之實現 Laravel 路由註冊功能Laravel路由
- Transformer各層網路結構詳解!面試必備!(附程式碼實現)ORM面試
- BAT面試必問細節:關於Netty中的ByteBuf詳解BAT面試Netty
- 面試官:展開說說,Spring中Bean物件是如何通過註解注入的?面試SpringBean物件
- HashMap的實現原理 HashMap底層實現,hashCode如何對應bucket?HashMap
- 註解式限流是如何實現滴
- MySQL Join的底層實現原理MySql
- 解析ArrayList的底層實現(上)
- iOS面試題答案 --- 底層iOS面試題
- iOS底層面試題--RuntimeiOS面試題
- iOS底層面試題--RunLoopiOS面試題OOP
- iOS底層面試總結iOS面試