一、java中元注解有四个: @Retention @Target @Document @Inherited;
(1)@Retention:描述注解的生命周期;
参数:枚举 RetentionPolicy
1)source:源码级别,编译后失效;
2)class:二进制级别,编译有效,运行失效;
3)runtime:运行时级别,该注解在运行时仍然有效;
(2)@Target:注解的作用目标
参数:枚举 ElementType
1)ANNOTATION_TYPE :注释类型声明(接口、类、枚举、注解)
2)CONSTRUCTOR:构造方法声明
3)FIELD:字段声明(包括枚举常量)
4)LOCAL_VARIABLE:局部变量声明
5)METHOD:方法声明
6)PACKAGE:包声明
7)PARAMETER:参数声明
8)TYPE:类、接口(包括注释类型)或枚举声明
9)TYPE_PARAMETER:用于标注类型参数;//1.8
10)TYPE_USE:可以标注任何类型名称;//1.8
(3)@Documented:javadoc文档注解(说明该注解将被包含在javadoc中);
(4)@Inherited:自动继承注解(注解标记其他的注解用于指明标记的注解是可以被自动继承的);
注意:此注解只对注解标记的超类有效,对接口是无效的。
二、自定义注解
1.创建自定义注解
@Documented
@Target({ElementType.TYPE,ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
public @interface TestAnnotion {
String desc() default "";
String value() default "";
}
2.创建自定义注解AOP类(用于拦截自定义注解)
必须要返回 joinPoint.proceed();否则无法回到被拦截的方法中
@Aspect
@Component
public class MyAnnotionAop {
private static final Logger logger = LoggerFactory.getLogger(MyAnnotionAop.class);
@Around(value = "@annotation(testAnnotion)", argNames = "joinPoint, testAnnotion")
public Object getMyAnnotion(ProceedingJoinPoint joinPoint,TestAnnotion testAnnotion){
String desc = testAnnotion.desc();
String value = testAnnotion.value();
try {
return joinPoint.proceed();
} catch (Throwable throwable) {
throwable.printStackTrace();
}
return "aaa";
}
}
3.使用注解
@RequestMapping("/annoTest")
@Controller
public class TestController {
@RequestMapping("anno")
@TestAnnotion(value = "test",desc = "测试")
public void testAnno(){
System.out.println("测试自定义注解");
for(int i=0;i<1000;i++){
System.out.println(i);
}
}
}