Junior
What is the difference between @RequestMapping and @PutMapping annotations in Spring?
sobes.tech AI
Answer from AI
@RequestMapping — a universal annotation for mapping web requests to handler methods. It allows specifying the HTTP method (GET, POST, PUT, DELETE, PATCH), path, parameters, headers, request and response content types.
@PutMapping — a specialized annotation, which is a shorthand for @RequestMapping(method = RequestMethod.PUT). It is used exclusively for mapping HTTP PUT requests to handler methods.
Main difference: @RequestMapping is more general and configurable, while @PutMapping is specific to the resource update operation (PUT).
Example:
// Example of using @RequestMapping to handle a PUT request
@RequestMapping(value = "/users/{id}", method = RequestMethod.PUT)
public ResponseEntity<User> updateUser(@PathVariable Long id, @RequestBody User userDetails) {
// User update logic
return ResponseEntity.ok(updatedUser);
}
// Example of using @PutMapping for the same
@PutMapping("/users/{id}")
public ResponseEntity<User> updateUser(@PathVariable Long id, @RequestBody User userDetails) {
// User update logic
return ResponseEntity.ok(updatedUser);
}