controlleraopspring-aoppointcut

Spring AOP for controller inside package


I am looking for a pointcut expression that might satisfy my needs, I have already figured one out but seems to be having some performance issues, and I believe there should be an easier solution.

I have a lot of packages like

What I wish to cover is all @RestController calls inside my v3 package. I guess it should be something like this but cant figure it out for now:

execution(* aaa.bbb.v3.*.* Controller( * ))

My solution for now was

@Pointcut(
  "within(@org.springframework.web.bind.annotation.RestController *) && " + 
  "execution(* aaa.bbb.v3.*..*(..))"
)

and it was working fine, but seems it has some performance issues as its analyzing all the code, and it should only be for controllers.


Solution

  • bean PCD could be used here and this answer assumes that the Spring controller beans are in a consistent fashion as given in the example .

    @Component
    @Aspect
    public class ControllerExcecutionAspect {
    
        @Pointcut("within(aaa.bbb.v3..*) && bean(*Controller))")
        public void v3Controller() {
        }
        
        @Before("v3Controller()")
        public void adviceBefore(JoinPoint jp) {
            System.out.println(jp.getSignature().toShortString());
        }
        
    }
    

    within : Any join point (method execution only in Spring AOP) within the v3 package or one of its sub-packages:

    bean : Any join point (method execution only in Spring AOP) on Spring beans having names that match the wildcard expression *Controller:

    Reference : https://docs.spring.io/spring-framework/docs/current/reference/html/core.html#aop-pointcuts-examples

    Do go through Writing Good Pointcuts section as well.