@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?
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.
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.
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.
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.
During application startup, Spring will identify all Bean
s 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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With