Spring AspectJ从ProceedingJoinPoint获取方法注释

时间:2017-07-24 12:22:01

标签: java spring annotations aspectj aspect

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

注释有一个枚举参数,我必须得到方面的值:

@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的Spring bean(只有实现类被注释)实现了一个接口 - pjp.getSignature()返回接口的签名,它没有注释。

没关系:

@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获取实现方法的签名?

2 个答案:

答案 0 :(得分:4)

管理:

@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);
        ...
    }
}

答案 1 :(得分:1)

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

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