Search code examples
springspring-bootspring-aop

Creating default pointcut spring aop


While to utilise the AOP to authorize request in my controllers, I used the approach that

there is default validation and specfic validation, so that the request for which I don't have specfic pointcut defined they are authorized by the default approach.

 @Before("execution(* com.example.controller.ExampleController.*(..))")
  public void validate() {
    validatePermissions("user", "create");
  }

 @Before("execution(* com.example.controller.*.*(..))")
  public void validateUser() {
    validatePermissions("admin", "admin");
  }

Problem is that even though I have specfic validation defined for User case Its even in case of request to my Example controller request is always going to default one.

what I want is that only request not already covered by other pointcut should go to the default pointcut


Solution

  • You would make the specific pointcut(s) reusable and reference them in && !specificPointcut() conditions, roughly like this (untested, just written in the browser):

    @Pointcut("execution(* com.example.controller.ExampleController.*(..))")
    public void specificPointcut() {}
    
    @Before("specificPointcut()")
    public void validate() {
      validatePermissions("user", "create");
    }
    
    @Before("execution(* com.example.controller.*.*(..)) && !specificPointcut()")
    public void validateUser() {
      validatePermissions("admin", "admin");
    }
    

    You can easily extend that to multiple specific pointcuts, either serially or hierarchically, depending on your situation.

    Serially excluding pointcuts would work like && !(specificPc1() || specificPc2()) and hierarchically by a more common level always excluding the next more specific one.