Search code examples
springspring-bootaopspring-aop

Do SpringBoot annotations like GetMapping use Spring AOP internally?


A maybe dumb question from a Spring Boot beginner.

I'm reading materials about AOP, and feel like the processing of a lot of annotations (including GetMapping and PostMapping) fits natually with AOP - we have a common concern (say, all functions annotated with GetMapping be treated as HTTP GET method) that is distributed over many different classes.

So does Spring internally use AOP to implement its handlers for stuff like GetMapping?


Solution

  • No, Spring does not use AOP in order to find the correct handler for the requested URI.

    That's essentially the job of the DispatcherServlet.

    @GetMapping, @PostMapping, @PutMapping, @PatchMapping, @DeleteMapping are all shortcuts for their respectives @RequestMapping annotations.

    The DispatcherServlet is a front controller that handles the incoming requests and delegates them to the correct handler.

    When a request arrives, the DispatcherServlet uses HandlerMappings and HandlerAdapters from the WebApplicationContext to delegate the request to the appropriate handler. Of course it's a lot more complicated then just that and there's a lot of engineering going on.

    The DispatcherServlet doesn't invoke the handler method directly, instead, the HandlerAdapter interface is used. Specifically, in the case of @RequestMapping annotations and it's shortcuts, the RequestMappingHandlerAdapter is used together with the RequestMappingHandlerMapping.

    The RequestMappingHandlerMapping is used by the DispatcherServlet to obtain the handler object (when using @RequestMapping in a class instead of a method) and the handler method (when using @RequestMapping and it's shortcuts in a method). This class is responsible for creating the RequestMappingInfo for each @RequestMapping annotated class or method, so, basically, it maps the corresponding handlers to it's paths.

    The RequestMappingHandlerAdapter is used to invoke the handler method through the RequestMappingHandlerAdapter#invokeHandlerMethod (see here)

    So no, Spring doesn't use AOP in this case. It's a lot of intelligent mapping going on.