java – Spring AspectJ从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批注的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获取实现方法的签名?

解决方法:

管理这样做:

@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);
        ...
    }
}
上一篇:java – AspectJ – 在运行时使用自定义ClassLoader进行编织


下一篇:Spring包作用