@pathvariable用于从restful url路径中提取变量值,支持单个/多个变量、类型转换、jsr-303校验及可选参数(required=false),但不支持默认值。

在 REST 接口开发中,@PathVariable 用于从 URL 路径中提取变量值,是 Spring MVC 提供的核心注解之一。它适用于设计符合 RESTful 风格的资源路径(如 /users/123、/orders/2024/05),让接口语义清晰、可读性强。
基本用法:绑定单个路径变量
URL 中用花括号 {} 定义占位符,方法参数用 @PathVariable 注解声明,Spring 会自动将对应路径段映射为参数值:
@GetMapping("/users/{id}")
public User getUserById(@PathVariable Long id) {
return userService.findById(id);
}
访问 GET /users/101 时,id 就会被解析为 101。默认情况下,参数名需与路径变量名一致;若不一致,需显式指定名称:
@GetMapping("/users/{userId}")
public User getUserById(@PathVariable("userId") Long id) {
return userService.findById(id);
}
多个路径变量同时使用
一个 URL 可含多个路径变量,每个都用 @PathVariable 绑定:
@GetMapping("/orders/{year}/{month}")
public List<order> getOrdersByYearMonth(
@PathVariable Integer year,
@PathVariable Integer month) {
return orderService.findByYearAndMonth(year, month);
}</order>
访问 /orders/2024/05 即可正确提取两个参数。也可混合使用 @PathVariable 和 @RequestParam(如分页参数):
在 Java 中初始化和管理阿里云 SDK客户端。包括单例模式、线程安全、endpoint 与 region 配置、VPC 终端节点、同步与异步等。
-
@PathVariable:取自路径本身,不可省略(除非设required = false) -
@RequestParam:取自查询字符串,如?page=1&size=10
类型转换与合法性校验
Spring 会自动将路径段字符串转为目标类型(如 Long、Integer、String)。若转换失败(如传入非数字),默认返回 400 Bad Request。可在参数上加 @Valid 或自定义校验:
@GetMapping("/users/{id}")
public User getUserById(@PathVariable @Min(1) Long id) {
return userService.findById(id);
}
注意:@PathVariable 支持 JSR-303 校验,但需开启验证支持(如添加 @Validated 到类或方法上)。
可选路径变量与默认值
路径变量默认必须存在。如需设为可选,需配合 required = false,并使用包装类型或 Optional:
@GetMapping("/products/{category}/{subCategory}")
public List<product> getProducts(
@PathVariable String category,
@PathVariable(required = false) String subCategory) {
return productService.findByCategory(category, subCategory);
}</product>
此时 /products/electronics 合法(subCategory 为 null),但 /products 仍非法(category 是必需的)。不支持直接设默认值,如需默认行为,建议在业务逻辑中处理 null。










