Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Spring AspectJ get method annotation from ProceedingJoinPoint

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?

like image 588
Evgeni Dimitrov Avatar asked Jan 30 '23 22:01

Evgeni Dimitrov


2 Answers

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);
        ...
    }
}
like image 67
Evgeni Dimitrov Avatar answered Feb 02 '23 11:02

Evgeni Dimitrov


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();
}
like image 23
atul ranjan Avatar answered Feb 02 '23 11:02

atul ranjan