有时需要使用Spring Boot自定义注解来快捷的实现功能。本实例演示如何自定义注解,以及实现响应的业务逻辑处理。

1.创建自定义注解类

@Target({ElementType.METHOD, ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Component
public @interface MyTestAnnotation {
    String value();
}

代码解释如下。

使用@Target注解标注作用范围。
使用@Retention标注生命周期。
使用@Documented将注解信息添加在Java文档中。
2.实现业务逻辑
以AOP的方式实现业务逻辑,见以下代码:

@Aspect
@Component
public class TestAnnotationAspect {
//拦截被MyTestAnnotation注解的方法;如果需要拦截指定包(package)指定规则名称的方法,则可以使用表达式execution(...)
@Pointcut("@annotation(com.example.demo.MyTestAnnotation)")
public void myAnnotationPointCut() {
}
@Before("myAnnotationPointCut()")
public void before(JoinPoint joinPoint) throws Throwable {
MethodSignature sign = (MethodSignature) joinPoint.getSignature();
Method method = sign.getMethod();
MyTestAnnotation annotation = method.getAnnotation(MyTestAnnotation.class);
//获取注解参数
System.out.print("TestAnnotation 参数:" + annotation.value());
}
}

  

3.使用自定义注解
在需要使用的地方使用自定义的注解,直接添加注解名即可。见以下代码:

@MyTestAnnotation("测试Annotation参数")
public void testAnnotation() {
}

  

运行上面代码,输出如下:

TestAnnotation 参数:测试Annotation参数

内容摘至《Spring Boot 实战派》