原文网址:Spring工具类--AnnotatedElementUtils的使用_IT利刃出鞘的博客-CSDN博客
简介
本文介绍Spring的AnnotatedElementUtils工具类的使用。
AnnotatedElementUtils与AnnotationUtils的不同之处在于:AnnotatedElementUtils可以通过父注解获得子注解上的值,而后者不能。
用法
注解
package com.example.annotation;import org.springframework.core.annotation.AliasFor;import java.lang.annotation.*;@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.METHOD, ElementType.TYPE})
@Documented
@Inherited
public @interface MyAnnotation {@AliasFor(attribute = "location")String value() default "";@AliasFor(attribute = "value")String location() default "";
}
package com.example.annotation;import org.springframework.core.annotation.AliasFor;import java.lang.annotation.*;@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.METHOD, ElementType.TYPE})
@Documented
@Inherited
@MyAnnotation
public @interface SubMyAnnotation {@AliasFor(annotation = MyAnnotation.class)String location() default "";// 这个不能写,只能有一个与父属性名同名的属性,否则报错
// @AliasFor(annotation = MyAnnotation.class)
// String value() default "";
}
控制器
package com.example.controller;import com.example.annotation.MyAnnotation;
import com.example.annotation.SubMyAnnotation;
import org.springframework.core.annotation.AnnotatedElementUtils;
import org.springframework.core.annotation.AnnotationUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;@RestController
@RequestMapping("/hello")
public class HelloController {@SubMyAnnotation(location = "location(my)")@RequestMapping("/test")public String test() {SubMyAnnotation subMyAnnotation = null;MyAnnotation myAnnotation = null;MyAnnotation myAnnotation1 = null;try {subMyAnnotation = AnnotationUtils.getAnnotation(this.getClass().getMethod("test"), SubMyAnnotation.class);myAnnotation = AnnotationUtils.getAnnotation(this.getClass().getMethod("test"), MyAnnotation.class);myAnnotation1 = AnnotatedElementUtils.getMergedAnnotation(this.getClass().getMethod("test"), MyAnnotation.class);} catch (NoSuchMethodException e) {e.printStackTrace();}return "loation(sub):" + subMyAnnotation.location() + "\n" +"location:" + myAnnotation.location() + "\n" +"location:" + myAnnotation1.location();}
}
测试
前端访问:http://localhost:8080/hello/test
结果
loation(sub):location(my)
location:
location:location(my)