4

I have an aspect that handles all methods that have a custom annotation.

The annotation has an enum parameter and I have to get the value in the aspect:

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

My case is very similar to that question and the accepted answer works for Spring beans that do not implement an interface.

The aspect:

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

But if the Spring bean that is annotated with @Monitored (only the implementation class is annotated) implements an interface - pjp.getSignature() returns the signature of the interface and it does not have an annotation.

This is OK:

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

This does not work - pjp.getSignature() gets the signature of the interface.

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

Is there a way to get the signature of the implementation method from ProceedingJoinPoint?

Evgeni Dimitrov
  • 21,976
  • 33
  • 120
  • 145

2 Answers2

8

Managed to do it with:

@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);
        ...
    }
}
Evgeni Dimitrov
  • 21,976
  • 33
  • 120
  • 145
5

If you have your custom annotation then the best way is :

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