@RequestMapping注解可以用于哪个层次的映射
时间: 2024-11-25 14:12:57 浏览: 21
@RequestMapping注解是Spring MVC中的一个核心注解,用于指定HTTP请求映射,它可以用于以下几个层次的映射:
1. **类级别(Controller)**:当您将其放在控制器类上时,表示该类下的所有公开方法都将处理特定的URL或HTTP动作(如GET、POST等)。例如:
```java
@RestController
@RequestMapping("/api/users")
public class UserController {
// 所有以/public/api/users开头的方法都会被映射
}
```
2. **方法级别(Action)**:当您在其上放置在控制器方法上时,仅指定该方法对应的具体路由和HTTP动作。比如:
```java
@GetMapping("/users/{id}")
@RequestMapping(value = "/singleUser", method = RequestMethod.GET)
public User getUser(@PathVariable Long id) {
// 只有这个方法会响应GET /singleUser 和 GET /api/users/{id} 的请求
}
```
3. **Handler方法**:在方法级别也可以进一步细化到处理器方法,比如@ExceptionHandler用于异常处理。
总之,@RequestMapping可以根据您的需求提供精细粒度的URL控制,让你的RESTful API设计更加清晰。
阅读全文