Spring AspectJ 从 ProceedingJoinPoint 获取方法注解

Spring AspectJ get method annotation from ProceedingJoinPoint

我有一个方面可以处理所有具有自定义注释的方法。

注释有一个枚举参数,我必须在方面获取值:

@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
public @interface Monitored {
    MonitorSystem monitorSystem();
}

我的情况与 question 非常相似,接受的答案适用于 Spring 未实现接口的 bean。

看点:

@Aspect
@Component
public class MonitorAspect {

    @Around("@annotation(com.company.project.monitor.aspect.Monitored)")
    public Object monitor(ProceedingJoinPoint pjp) throws Throwable {
        MethodSignature signature = (MethodSignature) pjp.getSignature();
        MonitorSystem monitorSystem = signature.getMethod().getAnnotation(Monitored.class).monitorSystem();
        ...
    }
}

但是如果用@Monitored注解的Springbean(只注解了实现class)实现了一个接口——pjp.getSignature()returns接口的签名,它没有注释。

这没问题:

@Component
public class SomeBean {
   @Monitored(monitorSystem=MonitorSystem.ABC) 
   public String someMethod(String name){}
}

这不起作用 - pjp.getSignature() 获取接口的签名。

@Component
public class SomeBeanImpl implements SomeBeanInterface {
   @Monitored(monitorSystem=MonitorSystem.ABC) 
   public String someMethod(String name){}
}

有没有办法从ProceedingJoinPoint获取实现方法的签名?

设法做到了:

@Aspect
@Component
public class MonitorAspect {

    @Around("@annotation(com.company.project.monitor.aspect.Monitored)")
    public Object monitor(ProceedingJoinPoint pjp) throws Throwable {
        MethodSignature signature = (MethodSignature) pjp.getSignature();
        Method method = pjp.getTarget()
           .getClass()
           .getMethod(signature.getMethod().getName(),     
                      signature.getMethod().getParameterTypes());
        Monitored monitored = method.getAnnotation(Monitored.class);
        ...
    }
}

如果您有自定义注释,那么最好的方法是:

@Around("@annotation(monitored)")
public Object monitor(ProceedingJoinPoint pjp, Monitored monitored ) throws 
  Throwable {
 MonitorSystem monitorSystem = monitored.monitorSystem();
 //your work .......
 pjp.proceed();
}