Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How @RequestMapping internally works in Spring Boot?

@RestController
@RequestMapping("/employee")
public class Employee {
  @RequestMapping("/save")
  public void saveEmployee() {
    // saving employee
  }
}

How does @RequestMapping will work internally to map the request to the saveEmployee method?

like image 339
Rachit Munjal Avatar asked Jul 26 '17 14:07

Rachit Munjal


People also ask

What does @RequestMapping do in spring boot?

RequestMapping annotation is used to map web requests onto specific handler classes and/or handler methods. @RequestMapping can be applied to the controller class as well as methods.

How does spring boot application works internally?

Spring Boot automatically configures your application based on the dependencies you have added to the project by using @EnableAutoConfiguration annotation. For example, if MySQL database is on your classpath, but you have not configured any database connection, then Spring Boot auto-configures an in-memory database.

What will happen if handler methods @RequestMapping?

Using @RequestMapping With HTTP Methods In the code snippet above, the method element of the @RequestMapping annotations indicates the HTTP method type of the HTTP request. All the handler methods will handle requests coming to the same URL ( /home), but will depend on the HTTP method being used.

Is @RequestMapping mandatory at class level?

A @RequestMapping on the class level is not required. Without it, all paths are simply absolute, and not relative. This means if you specify the class level annotations, the URL shall be relative, it shall be http://localhost:8080/users/user (URL to Handler mapping) and likewise.


1 Answers

During application startup, Spring will identify all Beans by way of XML Config, Java Config, or Component Scanning and store them in the ApplicationContext.

Spring Boot autoconfigures many Beans for you, including RequestMappingHandlerMapping.

When this Bean is initialized it scans the ApplicationContext for any Beans annotated with @Controller.

Then it iterates over each Controller bean and looks for methods annotated with @RequestMapping. Finally it persists these mapping/handler pairs in the MappingRegistry

The DispatcherServlet is the central HTTP request handler for your application and it will search the ApplicationContext for any Beans that implement the HandlerMapping interface, which the RequestMappingHandlerMapping Bean does (by way of inheritance).

Then it iterates over these beans asking them to resolve the corresponding handler for this request. The RequestMappingHandlerMapping bean will resolve the handler by searching its MappingRegistry.

When a match is found, the handler method is eventually invoked.

like image 164
Kyle Anderson Avatar answered Oct 06 '22 01:10

Kyle Anderson