最新国产好看的视频,伊人天堂AV在线,国产Aaaaaa视频,蜜臀视频在线观看一区,人妻av色图,密臀久久久精品影片,青青视频免费观看毛片,久草在线观看视,国产三级精品色情在线

SpringBoot?實(shí)現(xiàn)自定義的?@ConditionalOnXXX?注解示例詳解

 更新時(shí)間:2022年08月31日 10:01:35   作者:tytler  
這篇文章主要介紹了SpringBoot?實(shí)現(xiàn)自定義的?@ConditionalOnXXX?注解,通過(guò)示例代碼介紹了實(shí)現(xiàn)一個(gè)自定義的?@Conditional?派生注解,Conditional?派生注解的類如何注入到?spring?容器,需要的朋友可以參考下

實(shí)現(xiàn)一個(gè)自定義的 @Conditional 派生注解

自定義一個(gè)注解,繼承 @Conditional 注解

// 派生注解
@Retention(RetentionPolicy.RUNTIME)
@Target({ ElementType.TYPE, ElementType.METHOD })
@Documented
@Conditional(CustomConditional.class)
public @interface ConditionalOnCustom {
    String[] value() default {};
}

注解的處理類

public class CustomConditional implements Condition {

	@Override
	public boolean matches(ConditionContext context, AnnotatedTypeMetadata metadata) {
		// 獲取到自定義注解中的 value 值
		String[] properties = (String[]) metadata.getAnnotationAttributes("smoketest.test.condition.ConditionalOnCustom").get("value");
		// 遍歷自定義屬性的 value 值
		for (String property : properties) {
			// 獲取定義在配置文件中的值,并且 equals("customBean") 則返回 true
			if ("customBean".equals(context.getEnvironment().getProperty(property))) {
				return true;
			}
		}
		return false;
	}
}

使用注解

@Component
@ConditionalOnCustom({"smoketest.test.condition.bean"})
public class ConditionalUse {
}

application.properties 中配置變量

smoketest.test.condition.bean = customBean

獲取 ConditionalUse 對(duì)象

@SpringBootApplication
@ConfigurationPropertiesScan
public class SampleTestApplication {

	public static void main(String[] args) {
		ConfigurableApplicationContext context = SpringApplication.run(SampleTestApplication.class, args);
		ConditionalUse bean = context.getBean(ConditionalUse.class);
		System.out.println(bean);
	}

}

程序啟動(dòng)可以看到成功獲取 ConditionalUse 對(duì)象

Conditional 派生注解的類如何注入到 spring 容器

@Conditional 注解在 spring 的 ConfigurationClassParse 類中會(huì)調(diào)用 ConditionEvaluator.shouldSkip() 方法進(jìn)行判斷,Condition 接口的 matches() 是否返回 true,如果返回 true,就實(shí)例化對(duì)象,并注冊(cè)到 spring 容器中

  • shouldSkip() 這個(gè)方法執(zhí)行的邏輯主要是如果是解析階段則跳過(guò),如果是注冊(cè)階段則不跳過(guò)
  • 如果是在注冊(cè)階段即 REGISTER_BEAN 階段的話,此時(shí)會(huì)得到所有的 Condition 接口的具體實(shí)現(xiàn)類并實(shí)例化這些實(shí)現(xiàn)類,然后再執(zhí)行下面關(guān)鍵的代碼進(jìn)行判斷是否需要跳過(guò)
  • if ((requiredPhase == null || requiredPhase == phase) && !condition.matches(this.context, metadata)) { return true; }
  • 上面代碼最重要的邏輯是調(diào)用 Condition 接口的具體實(shí)現(xiàn)類的 matches() 方法,若 matches() 返回 false,則跳過(guò),不進(jìn)行注冊(cè) bean 的操作
  • 若 matches() 返回 true,則不跳過(guò),進(jìn)行注冊(cè) bean 的操作

到此這篇關(guān)于SpringBoot 實(shí)現(xiàn)自定義的 @ConditionalOnXXX 注解示例詳解的文章就介紹到這了,更多相關(guān)SpringBoot @ConditionalOnXXX 注解內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!

相關(guān)文章

最新評(píng)論

惠东县| 阿拉善盟| 德江县| 灵川县| 台安县| 渝中区| 康定县| 陕西省| 雷波县| 诏安县| 景泰县| 清镇市| 河西区| 博客| 宁德市| 淮南市| 陕西省| 凤冈县| 师宗县| 叙永县| 赞皇县| 莱州市| 田阳县| 同德县| 都兰县| 乐至县| 延寿县| 祥云县| 大安市| 嘉善县| 夏河县| 普兰店市| 综艺| 万宁市| 登封市| 和平区| 石嘴山市| 兰考县| 上饶县| 唐海县| 三明市|