您似乎对 spring 中的控制器如何工作感到困惑。
控制器是singleton,它在应用程序启动时创建,并调用其方法来处理传入请求。
因为您的控制器不是为每个请求创建的,而是在处理任何请求之前创建的,所以您不能在构造函数中使用路径变量 - 既因为在创建实例时没有关于它的值的信息,也因为您将希望它反映当前正在处理的请求,并且由于控制器可以同时处理许多多个请求,因此您不能将其存储为类属性,否则多个请求会相互干扰。
要实现您想要的,您应该使用方法并组合它们,如下所示:
@RestController
public class ContentController {
@GetMapping("/specialContent")
public Map<String, String> handleSpecialContent() {
Map<String, String> map = handleContent("specialContent");
map.put("special", "true");
return map;
}
@GetMapping("/{content}")
public Map<String, String> handleContent(@PathVariable String content) {
HashMap<String, String> map = new HashMap<>();
map.put("content", content);
return map;
}
}
注意{content:^(?!specialContent$).*$} 中的正则表达式,以确保 Spring 永远不会将 specialContent 路由到那里。你可以得到正则表达式 here 的解释并玩弄它here。
如果我们进行测试,您会发现它有效:
$ http localhost:8080/test
HTTP/1.1 200
Content-Type: application/json;charset=UTF-8
Date: Thu, 01 Feb 2018 08:18:11 GMT
Transfer-Encoding: chunked
{
"content": "test"
}
$ http localhost:8080/specialContent
HTTP/1.1 200
Content-Type: application/json;charset=UTF-8
Date: Thu, 01 Feb 2018 08:18:15 GMT
Transfer-Encoding: chunked
{
"content": "specialContent",
"special": "true"
}