简体   繁体   中英

Spring Boot 2 after aop annotation

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( F inalEvent), 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?

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM