0

I'm new in Spring Boot AOP.

Does an AOP method annotated with @Before run before java validation annotations (such as @NotNull)?

I have some other custom validations that need to run for every request but I need to run these validations after java validation annotations run.

Which one will run first?

my Controller:

@RestController
@RequestMapping("/users")
public class UserController {

    private final UserService userService;

    @Autowired
    public UserController(UserService userService) {
        this.userService = userService;
    }

    @PostMapping(value = "")
    public List<User> getAllUsers(@Valid @RequestBody User user) {
        return userService.getAllUsers();
    }
}

and my advice:

@Aspect
@Component
public class AspectConfig {

    @Pointcut(value = "within(@org.springframework.web.bind.annotation.RestController *)")
    public void restControllers() {

    }

    @Before(value = "restControllers()")
    public void logRequest(JoinPoint joinPoint) { 
         ...
    }

}

DwB
  • 37,124
  • 11
  • 56
  • 82
erfanmorsali
  • 155
  • 7
  • in my controller .. ill edit my question . – erfanmorsali Dec 14 '21 at 13:26
  • From your advice, t guess you use aspectj and create pointcuts for any method in RestController, so your advice will be invoked firstly, later validator ... You can add console log to see it if you config aop correctly... – Huy Nguyen Dec 14 '21 at 13:41
  • this is why i made this question..in this example @Valid is calling first..but i have another project that have almost same stracture like this.but in that project advice is calling first :/ – erfanmorsali Dec 14 '21 at 13:44
  • to advice controller, you should use @EnableAspectJAutoProxy. https://stackoverflow.com/a/10449728/1439560 – Huy Nguyen Dec 14 '21 at 14:08
  • 2
    Why use AOP for custom validations? Write a proper validator which does that so you can include it in the validation step. Or you are confusing validation for seomething different. If it is run before or after depends on how validation is used. – M. Deinum Dec 14 '21 at 15:10

1 Answers1

0

Does an AOP method annotated with @Before run before java validation annotations

No, it runs afterwards, just like you wish. See also this question. So you should be all set. Your logging advice should only be triggered if validation was successful, because only then the target method will be called.

You can implement a HandlerInterceptor if you wish to log/do something on the request level before validators kick in, see here.

kriegaex
  • 63,017
  • 15
  • 111
  • 202