Spring自定义注解

120 阅读1分钟

1.自定义注解

注解的作用就是声明aop的切入点,切入点就是动态代理需要增强的地方。

@Target({ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
public @interface MailSender {
   String value() default "";

   String content() default "";

   boolean active() default true;

   String subject() default "";
}

2.编写切面类

切面类里写的是你需要增强的逻辑。

@Aspect
@Component
public class MailSenderMonitor {

   @AfterReturning(value = "@annotation(com.liwei.test.liwei01.MailSender)", returning = "result")
   public void afterReturning(JoinPoint joinPoint, Object result) {
      MethodSignature ms = (MethodSignature) joinPoint.getSignature();
      Method method = ms.getMethod();

      boolean active = method.getAnnotation(MailSender.class).active();
      if(!active) return;

      String content = method.getAnnotation(MailSender.class).content();
      String subject = method.getAnnotation(MailSender.class).subject();

      System.out.println(content);
      System.out.println(subject);
      System.out.println(result);
   }
}

3.测试

@Service
public class Test {
   @MailSender(content = "上山打老虎", subject = "打老虎")
   public String test() {
      return "返回结果";
   }
}
@RestController
public class TestController {
   @Resource
   private Test test;

   @GetMapping("/test")
   public String test() {
      return test.test();
   }

   public static void main(String[] args) {
      String a = "aaa";
      String b = "aaa";
      System.out.println(a == b);
      System.out.println(a.equals(b));
   }
}

调用该接口后,控制台打印

上山打老虎
打老虎
返回结果