@AliasFor 注解的使用和源碼追蹤

第一種情況

可以作為別名姑原,比如,當(dāng)向注解AliasForAnnotation 的屬性location賦值時瞬浓,我們可以這樣寫AliasForAnnotation (location="/s/b")轧钓,但是能不能省掉location呢?也就是AliasForAnnotation ("/s/b")冒滩,可以
的,因?yàn)樽⒔舛x了飞涂,當(dāng)屬性值是value就可以旦部,那就向AliasForAnnotation 新增一個value屬性即可,但是當(dāng)你AliasForAnnotation ("/s/b")時较店,location沒有值,那如何做到既可以AliasForAnnotation ("/s/b")容燕,location也有值呢梁呈?可以使用spring提供的 @AliasFor,但是這個注解需要結(jié)合AnnotationUtils.findAnnotation或者AnnotatedElementUtils.findMergedAnnotation才能有效

注意事項(xiàng)

來自https://blog.csdn.net/weixin_43564627/article/details/93871075

1.組成別名對的每個屬性都必須用@AliasFor進(jìn)行注釋,并且AliasFor中的值
必須指向別名對中的另一個屬性
2.別名化的屬性必須聲明相同的返回類型
3.別名化的屬性必須聲明默認(rèn)值
4.別名化的屬性默認(rèn)值必須相同

import org.springframework.core.annotation.AliasFor;
import java.lang.annotation.*;

/**
 * @author lwh
 * @date 2022/3/15
 */
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface AliasForAnnotation {

    
    @AliasFor("location")
     String value() default "";

    @AliasFor("value")
     String location() default "";
}

import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.core.annotation.AnnotationUtils;
import org.springframework.stereotype.Component;
import org.springframework.test.context.junit4.SpringRunner;

import java.lang.annotation.Annotation;

/**
 * @author lwh
 * @date 2022/3/15
 */
@AliasForAnnotation(location = "/spring/value")
public class AliasForTest {


    @Test
    public  void test01(){
        final AliasForAnnotation annotation = AnnotationUtils.findAnnotation(AliasForTest.class, AliasForAnnotation.class);
        System.out.println(annotation.value());
        System.out.println(annotation.location());
    }
}

//輸出
/spring/value
/spring/value

源碼追蹤

1.AnnotationUtils.findAnnotation

2.AnnotationUtils.synthesizeAnnotation

//返回別名值的策略蘸秘,使用了策略模式
DefaultAnnotationAttributeExtractor attributeExtractor =
                new DefaultAnnotationAttributeExtractor(annotation, annotatedElement);

//動態(tài)代理InvocationHandler 官卡,傳入返回別名值的策略蝗茁。
InvocationHandler handler = new SynthesizedAnnotationInvocationHandler(attributeExtractor);

Class<?>[] exposedInterfaces = new Class<?>[] {annotationType, SynthesizedAnnotation.class};

//動態(tài)代理,使用了代理模式
return (A) Proxy.newProxyInstance(annotation.getClass().getClassLoader(), exposedInterfaces, handler);

3.使用動態(tài)代理寻咒,當(dāng)執(zhí)行被代理類時哮翘,會執(zhí)行InvocationHandler 的invoke

//來自AnnotationUtils.synthesizeAnnotation
InvocationHandler handler = new SynthesizedAnnotationInvocationHandler(attributeExtractor);

//SynthesizedAnnotationInvocationHandler的invoke
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
        if (ReflectionUtils.isEqualsMethod(method)) {
            return annotationEquals(args[0]);
        }
        if (ReflectionUtils.isHashCodeMethod(method)) {
            return annotationHashCode();
        }
        if (ReflectionUtils.isToStringMethod(method)) {
            return annotationToString();
        }
        if (AnnotationUtils.isAnnotationTypeMethod(method)) {
            return annotationType();
        }
        if (!AnnotationUtils.isAttributeMethod(method)) {
            throw new AnnotationConfigurationException(String.format(
                    "Method [%s] is unsupported for synthesized annotation type [%s]", method, annotationType()));
        }
        return getAttributeValue(method);
    }

4.SynthesizedAnnotationInvocationHandler.getAttributeValue

private Object getAttributeValue(Method attributeMethod) {
        String attributeName = attributeMethod.getName();
        Object value = this.valueCache.get(attributeName);
        if (value == null) {
//this.attributeExtractor,不就是第2步傳進(jìn)來的返回別名值的策略嗎?
            value = this.attributeExtractor.getAttributeValue(attributeMethod);
            if (value == null) {
                String msg = String.format("%s returned null for attribute name [%s] from attribute source [%s]",
                        this.attributeExtractor.getClass().getName(), attributeName, this.attributeExtractor.getSource());
                throw new IllegalStateException(msg);
            }

        
            if (value instanceof Annotation) {
                value = AnnotationUtils.synthesizeAnnotation((Annotation) value, this.attributeExtractor.getAnnotatedElement());
            }
            else if (value instanceof Annotation[]) {
                value = AnnotationUtils.synthesizeAnnotationArray((Annotation[]) value, this.attributeExtractor.getAnnotatedElement());
            }

            this.valueCache.put(attributeName, value);
        }

        // Clone arrays so that users cannot alter the contents of values in our cache.
        if (value.getClass().isArray()) {
            value = cloneArray(value);
        }

        return value;
    }

5.DefaultAnnotationAttributeExtractor.getAttributeValue()

    public final Object getAttributeValue(Method attributeMethod) {
        String attributeName = attributeMethod.getName();
        Object attributeValue = getRawAttributeValue(attributeMethod);

        List<String> aliasNames = this.attributeAliasMap.get(attributeName);
        if (aliasNames != null) {
            Object defaultValue = AnnotationUtils.getDefaultValue(this.annotationType, attributeName);
            for (String aliasName : aliasNames) {
                Object aliasValue = getRawAttributeValue(aliasName);

                if (!ObjectUtils.nullSafeEquals(attributeValue, aliasValue) &&
                        !ObjectUtils.nullSafeEquals(attributeValue, defaultValue) &&
                        !ObjectUtils.nullSafeEquals(aliasValue, defaultValue)) {
                    String elementName = (this.annotatedElement != null ? this.annotatedElement.toString() : "unknown element");
                    throw new AnnotationConfigurationException(String.format(
                            "In annotation [%s] declared on %s and synthesized from [%s], attribute '%s' and its " +
                            "alias '%s' are present with values of [%s] and [%s], but only one is permitted.",
                            this.annotationType.getName(), elementName, this.source, attributeName, aliasName,
                            ObjectUtils.nullSafeToString(attributeValue), ObjectUtils.nullSafeToString(aliasValue)));
                }


                if (ObjectUtils.nullSafeEquals(attributeValue, defaultValue)) {
                    //重點(diǎn)毛秘,需要的屬性值=別名的屬性值
                    attributeValue = aliasValue;
                }
            }
        }

        return attributeValue;
    }

第二個例子

我們都知道注解是不能繼承另一個注解的饭寺,當(dāng)我們想復(fù)用某一個注解的屬性時,根本無法做到叫挟,但是有了AliasFor艰匙,你可向另外一個注解注入屬性值,請結(jié)合這個類使AnnotatedElementUtils.findMergedAnnotation抹恳,\color{red}{在我測試的時候AnnotationUtils.findAnnotation獲取不到值员凝,知道的可以教我一下}

注意事項(xiàng)

來自https://blog.csdn.net/weixin_43564627/article/details/93871075

1 如果一個屬性是一個元注解屬性的別名,那么這個屬性必須用@AliasFor進(jìn)行注釋并且
該屬性必須指向元注解屬性。
2 別名化的屬性必須聲明相同的返回結(jié)果
3.@AliasFor的annotation屬性必須引用元注解
4.被引用的元注解必須放置在聲明了@AliasFor的注解類上


import org.springframework.core.annotation.AliasFor;

import java.lang.annotation.*;

/**
 * @author lwh
 * @date 2022/3/16
 */
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface LocationAnnotation {
    @AliasFor("value")
    String location() default "";

    @AliasFor("location")
    String value() default "";
}

import org.springframework.core.annotation.AliasFor;

import java.lang.annotation.*;

/**
 * @author lwh
 * @date 2022/3/15
 */
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
@Documented
@LocationAnnotation //我使用了這個注解奋献,我希望可以賦值給它
public @interface AliasForAnnotation {

//當(dāng)向value賦值時健霹,LocationAnnotation的location屬性也會賦予到值
    @AliasFor(attribute = "location",annotation = LocationAnnotation.class ) 
     String value() default "";
}


import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.core.annotation.AnnotatedElementUtils;
import org.springframework.core.annotation.AnnotationUtils;
import org.springframework.stereotype.Component;
import org.springframework.test.context.junit4.SpringRunner;

import java.lang.annotation.Annotation;

/**
 * @author lwh
 * @date 2022/3/15
 */
@AliasForAnnotation( "/spring/value")
public class AliasForTest {


    @Test
    public  void test01(){
        final LocationAnnotation annotation = AnnotatedElementUtils.findMergedAnnotation(AliasForTest.class, LocationAnnotation.class);
        System.out.println(annotation.location());
    }
}

源碼追蹤(簡單的跟了一下,具體的可以自己查看瓶蚂,凌晨4.23骤公,哭了)

簡單的說,就是遞歸獲取到LocationAnnotation 注解扬跋,然后獲取到AliasForAnnotation 的value值阶捆,封裝成map,然后把這個值傳到MapAnnotationAttributeExtractor里這個值經(jīng)過一些判斷和處理钦听,然后進(jìn)行動態(tài)代理洒试,最后通過MapAnnotationAttributeExtractor的getAttributeValue獲取到值,getAttributeValue其實(shí)獲取的是之前傳過來的值

1. AnnotatedElementUtils.findMergedAnnotation

2. AnnotatedElementUtils.findMergedAnnotationAttributes

3. AnnotatedElementUtils.searchWithFindSemantics

4.AnnotatedElementUtils.searchWithFindSemantics//遞歸查找朴上,直到查找到LocationAnnotation 注解

image.png

5.MergedAnnotationAttributesProcessor.postProcess

6.MergedAnnotationAttributesProcessor.overrideAttributes

image.png

7. AnnotationUtils.synthesizeAnnotation(attributes, annotationType, element),換了MapAnnotationAttributeExtractor策略來處理別名值

image.png

8. SynthesizedAnnotationInvocationHandler(attributeExtractor)垒棋,動態(tài)代理執(zhí)行invoke()

image.png

執(zhí)行MapAnnotationAttributeExtractor策略的方法

image.png

9.MapAnnotationAttributeExtractor沒有g(shù)etAttributeValue方法,使用父類AbstractAliasAwareAnnotationAttributeExtractor的方法

image.png

image.png

image.png

image.png

image.png

image.png

image.png

image.png
image.png

image.png

參考文章
https://blog.csdn.net/weixin_43564627/article/details/93871075

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
  • 序言:七十年代末痪宰,一起剝皮案震驚了整個濱河市叼架,隨后出現(xiàn)的幾起案子,更是在濱河造成了極大的恐慌衣撬,老刑警劉巖乖订,帶你破解...
    沈念sama閱讀 221,548評論 6 515
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件,死亡現(xiàn)場離奇詭異具练,居然都是意外死亡乍构,警方通過查閱死者的電腦和手機(jī),發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 94,497評論 3 399
  • 文/潘曉璐 我一進(jìn)店門扛点,熙熙樓的掌柜王于貴愁眉苦臉地迎上來哥遮,“玉大人岂丘,你說我怎么就攤上這事∶咭” “怎么了奥帘?”我有些...
    開封第一講書人閱讀 167,990評論 0 360
  • 文/不壞的土叔 我叫張陵,是天一觀的道長仪召。 經(jīng)常有香客問我寨蹋,道長,這世上最難降的妖魔是什么返咱? 我笑而不...
    開封第一講書人閱讀 59,618評論 1 296
  • 正文 為了忘掉前任钥庇,我火速辦了婚禮,結(jié)果婚禮上咖摹,老公的妹妹穿的比我還像新娘评姨。我一直安慰自己,他們只是感情好萤晴,可當(dāng)我...
    茶點(diǎn)故事閱讀 68,618評論 6 397
  • 文/花漫 我一把揭開白布吐句。 她就那樣靜靜地躺著,像睡著了一般店读。 火紅的嫁衣襯著肌膚如雪嗦枢。 梳的紋絲不亂的頭發(fā)上,一...
    開封第一講書人閱讀 52,246評論 1 308
  • 那天屯断,我揣著相機(jī)與錄音文虏,去河邊找鬼。 笑死殖演,一個胖子當(dāng)著我的面吹牛氧秘,可吹牛的內(nèi)容都是我干的。 我是一名探鬼主播趴久,決...
    沈念sama閱讀 40,819評論 3 421
  • 文/蒼蘭香墨 我猛地睜開眼丸相,長吁一口氣:“原來是場噩夢啊……” “哼!你這毒婦竟也來了彼棍?” 一聲冷哼從身側(cè)響起灭忠,我...
    開封第一講書人閱讀 39,725評論 0 276
  • 序言:老撾萬榮一對情侶失蹤,失蹤者是張志新(化名)和其女友劉穎座硕,沒想到半個月后弛作,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體,經(jīng)...
    沈念sama閱讀 46,268評論 1 320
  • 正文 獨(dú)居荒郊野嶺守林人離奇死亡坎吻,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點(diǎn)故事閱讀 38,356評論 3 340
  • 正文 我和宋清朗相戀三年缆蝉,在試婚紗的時候發(fā)現(xiàn)自己被綠了。 大學(xué)時的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片瘦真。...
    茶點(diǎn)故事閱讀 40,488評論 1 352
  • 序言:一個原本活蹦亂跳的男人離奇死亡刊头,死狀恐怖,靈堂內(nèi)的尸體忽然破棺而出诸尽,到底是詐尸還是另有隱情原杂,我是刑警寧澤,帶...
    沈念sama閱讀 36,181評論 5 350
  • 正文 年R本政府宣布您机,位于F島的核電站穿肄,受9級特大地震影響,放射性物質(zhì)發(fā)生泄漏际看。R本人自食惡果不足惜咸产,卻給世界環(huán)境...
    茶點(diǎn)故事閱讀 41,862評論 3 333
  • 文/蒙蒙 一、第九天 我趴在偏房一處隱蔽的房頂上張望仲闽。 院中可真熱鬧脑溢,春花似錦、人聲如沸赖欣。這莊子的主人今日做“春日...
    開封第一講書人閱讀 32,331評論 0 24
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽顶吮。三九已至社牲,卻和暖如春,著一層夾襖步出監(jiān)牢的瞬間悴了,已是汗流浹背搏恤。 一陣腳步聲響...
    開封第一講書人閱讀 33,445評論 1 272
  • 我被黑心中介騙來泰國打工, 沒想到剛下飛機(jī)就差點(diǎn)兒被人妖公主榨干…… 1. 我叫王不留湃交,地道東北人熟空。 一個月前我還...
    沈念sama閱讀 48,897評論 3 376
  • 正文 我出身青樓,卻偏偏與公主長得像巡揍,于是被迫代替她去往敵國和親痛阻。 傳聞我的和親對象是個殘疾皇子,可洞房花燭夜當(dāng)晚...
    茶點(diǎn)故事閱讀 45,500評論 2 359

推薦閱讀更多精彩內(nèi)容