@Target({ElementType.METHOD, ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface MyFirstAnnotation {
String value() default "";
}
解释:
@Target 定义注解修饰的目标,有Method和类等;
@Retention 定义注解的生命周期,分为三种
1)源码级别:SOURCE,
2)编译器级别:CLASS
3)运行期级别:RUNTIME
@Documented 定义注解会被javadoc或者其他类似工具文档化
2.定义切面类
创建完自定义注解后,很显然的思路是如何让注解起作用。这里以输出日志的注解为例,当用自定义注解来修饰方法时,我们期望在方法执行的前后输出日志记录,那么我们必须采用AOP(面向切面编程)的思想,理所当然地,我们需要定义切面类:
@Aspect
@Component
public class MyFirstAspect {
@Pointcut("@annotation(MyFirstAnnotation)")
public void annotationPointcut() {
}
@Before("annotationPointcut()")
public void beforePointcut(JoinPoint joinPoint) {
MethodSignature methodSignature = (MethodSignature) joinPoint.getSignature();
Method method = methodSignature.getMethod();
MyFirstAnnotation annotation = method.getAnnotation(MyFirstAnnotation.class);
String value = annotation.value();
System.out.println("准备"+value);
}
@After("annotationPointcut()")
public void afterPointcut(JoinPoint joinPoint) {
MethodSignature methodSignature = (MethodSignature) joinPoint.getSignature();
Method method = methodSignature.getMethod();
MyFirstAnnotation annotation = method.getAnnotation(MyFirstAnnotation.class);
String value = annotation.value();
System.out.println("结束"+value);
}
}
重点需要关注的是:切点的定义,切点可以定义成execute(public String sayHello()) 的形式,但是这种形式就和咱们的注解不相关了,因此我们采用@annotation(MyFirstAnnotation) 的形式,这样切点就变成了我们自定义注解所修饰的方法 !
3.使用自定义注解
@MyFirstAnnotation("吃饭")
@RequestMapping(value = "/say")
public String sayHello() {
System.out.println("吃饭");
return "hello spring boot";
}
4.结果:
准备吃饭
吃饭
结束吃饭
你明白了吗。