当我们在Spring MVC或Spring Boot应用程序中使用@GetMapping注解时,它用于处理HTTP GET请求。
它是@RequestMapping(method = RequestMethod.GET)的一种快捷方式。
RequestMapping注解:
- 在Spring 4.3之前,将传入的HTTP请求URL映射到控制器方法的主要注解是@RequestMapping。
- 但是,Spring 4.3引入了更具体的每个HTTP请求类型的注解:
@GetMapping:处理HTTP GET请求。
@PostMapping:处理HTTP POST请求。
@PutMapping:处理HTTP PUT请求。
@DeleteMapping:处理HTTP DELETE请求。
@PatchMapping:处理HTTP PATCH请求。
@GetMapping的示例:
假设我们有一个REST控制器来管理用户数据。我们可以使用@GetMapping将特定的URI映射到控制器方法。
@RestController
public class UserController {
private final UserService userService;
@Autowired
public UserController(UserService userService) {
this.userService = userService;
}
@GetMapping("/users")
public ResponseEntity<List<User>> getAll() {
List<User> users = userService.getAll();
return ResponseEntity.ok(users);
在上面的示例中,@GetMapping(“/users”)将处理对/users路径的GET请求,并调用getAll()方法来获取所有用户的列表。如果请求成功,将返回一个包含用户列表的HTTP响应。