Spring AOP for controller inside package

803 Views Asked by At

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

  • aaa.bbb.v3.groups.GroupController,
  • aaa.bbb.v3.groups.GroupService,
  • aaa.bbb.v3.products.ProductController,
  • aaa.bbb.v3.products.ProductService.

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.

2

There are 2 best solutions below

0
On BEST ANSWER

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.

0
On

I am not sure if it is going to improve anything, but you could try (untested):

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

BTW, not seeing all your code, I have no way of knowing if you combine pointcuts and other parts of your total pointcut might use other, more expensive constructs, such as this(), target(), @target().