Discuss / Java / (总结)注解标示使用AOP

(总结)注解标示使用AOP

Topic source

定义一个注解或者使用已有的注解:

@Target(METHOD)
@Retention(RUNTIME)
public @interface AspectMethod {
    String value();
}

核心逻辑:

  • 依据注解在需要切面的地方标注
@Component
public class UserService {
    // 监控register()方法性能:
    @AspectMethod("register")
    public User register(String email, String password, String name) {
        ...
    }
    ...
}

切面方法:

  • @Aspect标示Bean
  • @拦截器("Annotation(切面方法参数)")
@Aspect
@Component
public class MetricAspect {
    //切面方法参数为method1
    @Around("@annotation(method1)")
    public Object metric(ProceedingJoinPoint joinPoint, AspectMethod method1) throws Throwable {
        String name = method1.value();
        long start = System.currentTimeMillis();
        try {
            //  模拟核心逻辑前运行方法
            System.err.println("我在register之前");   
            //  运行核心逻辑
            return joinPoint.proceed();
        } finally {
            long t = System.currentTimeMillis() - start;
            // 写入日志或发送至JMX:
            System.err.println("[AspectMethod] " + name + ": " + t + "ms");
        }
    }
}

哎呦,自己写的总结都看的好陌生了!


  • 1

Reply