@MatrixVariable用于提取URL路径段中的矩阵变量(如/path;name=value),需在WebMvcConfigurer中设置UrlPathHelper.setRemoveSemicolonContent(false)启用,支持绑定到指定路径变量、批量接收及Map形式解析。

@MatrixVariable 是 Spring MVC 提供的注解,用于从 URL 路径段中提取“矩阵变量”(matrix variables),即形如 /path;name1=value1;name2=value2 的键值对。它不是查询参数(?key=value),也不是路径变量({id}),而是附着在某个路径片段上的语义化元数据。
启用矩阵变量支持
Spring Boot 2.6+ 默认禁用矩阵变量,需手动开启。关键点有两个:
- 在 WebMvcConfigurer 中设置
UrlPathHelper.setRemoveSemicolonContent(false) - 确保服务器(如 Tomcat)不自动剥离分号内容(默认会删掉
;xxx)
配置示例:
@Configuration
public class WebConfig implements WebMvcConfigurer {
@Override
public void configurePathMatch(PathMatchConfigurer configurer) {
UrlPathHelper urlPathHelper = new UrlPathHelper();
urlPathHelper.setRemoveSemicolonContent(false); // 必须设为 false
configurer.setUrlPathHelper(urlPathHelper);
}
}
基本用法:单个矩阵变量
假设请求 URL 是:GET /users/123;role=admin;active=true
立即学习“Java免费学习笔记(深入)”;
控制器写法:
@GetMapping("/users/{id}")
public String getUser(
@PathVariable Long id,
@MatrixVariable String role,
@MatrixVariable(required = false) Boolean active) {
System.out.println("id=" + id + ", role=" + role + ", active=" + active);
return "user";
}
注意:@MatrixVariable 默认绑定到最近的路径变量所在段(这里是 {id} 对应的 123 段),所以 ;role=admin 必须紧挨着 123 出现。
指定路径段:使用 pathVar 属性
当 URL 含多个路径段且都有矩阵变量时(如 /org/abc;type=hr/dept;level=senior),需明确指定绑定目标:
@GetMapping("/org/{orgId}/dept/{deptId}")
public String getDept(
@PathVariable String orgId,
@PathVariable String deptId,
@MatrixVariable(pathVar = "orgId") String orgType, // 绑定到 /org/abc;type=hr 中的 abc 段
@MatrixVariable(pathVar = "deptId") String deptLevel) { // 绑定到 /dept;level=senior 中的 dept 段
// ...
}
接收多个同名矩阵变量或 Map 形式
支持批量解析:
-
@MatrixVariable List<string> tags</string>→ 解析/item;tags=a;tags=b;tags=c -
@MatrixVariable Map<string string> matrixVars</string>→ 自动收集当前路径段所有矩阵变量
示例:
@GetMapping("/item/{itemId}")
public String itemDetail(
@PathVariable String itemId,
@MatrixVariable List<String> tags,
@MatrixVariable Map<String, String> all) {
// tags = ["a", "b", "c"]
// all = {"tags": "c"} ← 注意:Map 只保留最后一个同名值(除非用 MultiValueMap)
}
若需保留全部同名值,改用 MultiValueMap<string string></string>:
@MatrixVariable MultiValueMap<String, String> matrixParams
矩阵变量适合表达资源的修饰性、非层级性的属性,比如版本、视图模式、过滤标签等,但需注意客户端和中间件(如 Nginx、网关)可能默认过滤分号,生产环境务必端到端验证。


















