简介
本文介绍Spring的AnnotationUtils工具类的用法。
AnnotatedElementUtils与AnnotationUtils的区别见:这里
用法
注解类
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.controller; import com.example.annotation.MyAnnotation; 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 { @MyAnnotation(location = "location(my)") @RequestMapping("/test") public String test() { MyAnnotation myAnnotation = null; try { myAnnotation = AnnotationUtils.getAnnotation(this.getClass().getMethod("test"), MyAnnotation.class); } catch (NoSuchMethodException e) { e.printStackTrace(); } return "loation:" + myAnnotation.location(); } }
测试
postman访问:http://localhost:8080/hello/test
postman结果
loation:location(my)
请先
!