第一種情況
可以作為別名姑原,比如,當(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抹恳,
注意事項(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 注解
5.MergedAnnotationAttributesProcessor.postProcess
6.MergedAnnotationAttributesProcessor.overrideAttributes
7. AnnotationUtils.synthesizeAnnotation(attributes, annotationType, element),換了MapAnnotationAttributeExtractor策略來處理別名值
8. SynthesizedAnnotationInvocationHandler(attributeExtractor)垒棋,動態(tài)代理執(zhí)行invoke()
執(zhí)行MapAnnotationAttributeExtractor策略的方法
9.MapAnnotationAttributeExtractor沒有g(shù)etAttributeValue方法,使用父類AbstractAliasAwareAnnotationAttributeExtractor的方法
參考文章
https://blog.csdn.net/weixin_43564627/article/details/93871075