亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

從 Spring 的“組合注釋”中獲取值

從 Spring 的“組合注釋”中獲取值

慕碼人8056858 2022-12-15 16:34:27
使用 Spring,您可以擁有某種組合注釋。一個突出的例子是@SpringBootApplication-annotation,它是 @Configuration,@EnableAutoConfiguration和的組合@ComponentScan。我正在嘗試獲取受某個注釋影響的所有 Bean,即ComponentScan.按照這個答案,我正在使用以下代碼:for (T o : applicationContext.getBeansWithAnnotation(ComponentScan.class).values()) {     ComponentScan ann = (ComponentScan) o.getClass().getAnnotation(ComponentScan.class);     ... }這是行不通的,因為并非所有返回的 beangetBeansWithAnnotation(ComponentScan.class)都確實用該注釋進行了注釋,因為那些被注釋@SpringBootApplication的(通常)不是?,F在我正在尋找某種通用的方法來檢索注釋的值,即使它只是作為另一個注釋的一部分添加。我怎樣才能做到這一點?
查看完整描述

2 回答

?
手掌心

TA貢獻1942條經驗 獲得超3個贊

事實證明,有一個實用程序集AnnotatedElementUtils可以讓您處理那些合并的注釋。


for (Object annotated : context.getBeansWithAnnotation(ComponentScan.class).values()) {

    Class clazz = ClassUtils.getUserClass(annotated) // thank you jin!

    ComponentScan mergedAnnotation = AnnotatedElementUtils.getMergedAnnotation(clazz, ComponentScan.class);

    if (mergedAnnotation != null) { // For some reasons, this might still be null.

        // TODO: useful stuff.

    }

}


查看完整回答
反對 回復 2022-12-15
?
jeck貓

TA貢獻1909條經驗 獲得超7個贊

它可能是 CglibProxy。所以不能直接獲取Annotation。


ClassUtils.isCglibProxyClass(o)

有關更多信息,請參閱此


編輯,你可以添加你的邏輯代碼。找到 ComponentScan。


if (ClassUtils.isCglibProxyClass(o.getClass())) {

            Annotation[] annotations = ClassUtils.getUserClass(o).getAnnotations();

            for (Annotation annotation : annotations) {

                ComponentScan annotation1 = annotation.annotationType().getAnnotation(ComponentScan.class);

// in my test code , ComponentScan can get here.for @SpringBootApplication 

                System.out.println(annotation1);

            }


        }


查看完整回答
反對 回復 2022-12-15
  • 2 回答
  • 0 關注
  • 87 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號