1

I am trying to create a @after aop annotation to execute a code after the method got completed. I am facing issues when I pass with parameter.

Aspect Code -

@Aspect
@Component
public class FinalAspect {

    @Pointcut("@annotation(finalEvent)")
    public void runFinalMethod() {}

    @After("runFinalMethod()")
    public void finalMethod(JoinPoint joinPoint, FinalEvent finalEvent) throws Throwable { 
       ....
    }
}

FinalEvent -

@Target({ElementType.Method})
@Retention(RetentionPolicy.RUNTIME)
public @interface FinalEvent {
   String value() default "";
}

Controller -

@FinalEvent(value = "test")
public ResponseEntity<String> getDetails() { ... }

This throws error:

error Type referred to is not an annotation type: finalEvent

But if I remove the "value" property from FinalEvent interface and change to @annotation(FinalEvent), it works. But I need to pass parameter.

If I modify to @Pointcut("@annotation(com.aspect.finalEvent)") then it throws error at ::0 formal unbound in pointcut.

How can I resolve this?

halfer
  • 19,824
  • 17
  • 99
  • 186
Lolly
  • 34,250
  • 42
  • 115
  • 150

1 Answers1

2

Following code would work

@Aspect
@Component
public class FinalAspect {

    @Pointcut("@annotation(finalEvent) && within(so.qn68380528.service..*)")
    public void runFinalMethod(FinalEvent finalEvent) {}

    @After("runFinalMethod(finalEvent)")
    public void finalMethod(FinalEvent finalEvent) throws Throwable { 
       System.out.println(finalEvent.value());
    }
}

Remember to limit the scope : https://docs.spring.io/spring-framework/docs/current/reference/html/core.html#writing-good-pointcuts

You may also go through this answer from @kriegaex to understand why an @annotation has a global scope.

R.G
  • 6,436
  • 3
  • 19
  • 28