Search code examples
springspring-aop

Spring AOP: execute code before validation in a controller


I have the following code:

   class OrderController {
      @AllowedScopes({ORDER_CREATE})
      @PostMapping("/create")
      public CreateOrderResponse createOrder(@Valid @RequestBody OrderRequest request){
      }
    }
    
    @Aspect
    @Component
    public class AllowedScopeAspect {
        @Pointcut("@annotation(allowedScopes)")
        private void callAtAllowedScopes(AllowedScopes allowedScopes) {
            // just a pointcut signature
        }
    
        @Before(value = "callAtAllowedScopes(allowedScopes)", argNames = "jp,allowedScopes")
        public void validateScope(JoinPoint jp, AllowedScopes allowedScopes) {
             ...
        }
}

Aspect code validates if user have required scope. The problem is Aspect code is executed after request body validation. If validation is not OKAY, it is returning validation error. if passes, returning 403 error.

How can I execute aspect code before data binding and validation or control handler stage?


Solution

  • You seem to misunderstand how the JVM works. Method parameters always need to be evaluated before calling the method, otherwise the JVM cannot put the parameters on the stack for the method to get access to them. Therefore, also validation takes place before calling the method.

    Spring AOP can only intercept method execution, i.e. an aspect is necessarily triggered after validation. The whole point of parameter validation is to not execute the corresponding method, if any parameter is invalid. But if the method is not executed in the first place, there is nothing to intercept for the aspect. 😉