【发布时间】:2020-05-07 10:01:35
【问题描述】:
我有以下控制器:
@RestController
@RequestMapping("/api/{brand}")
public class CarController {
private final CarService carService;
@Autowird
public CarController(CarService carService) {
this.carService = carService;
}
@GetMapping
public Resources<Car> getCars(@PathVariable("brand") String brand) {
return new Resources<>(carService.getCars(brand));
}
@GetMapping(value = "/{model}")
public Car getModel(@PathVariable("brand") String brand, @PathVariable("model") String model) {
return carService.getCar(brand, model);
}
}
我希望对http://localhost:8080/api/bmw 的http GET 调用返回getCars 方法的结果。相反,调用被委托给getModel 方法。这会返回错误,因为没有 {model} 路径变量。
为什么我的 http 调用被委派给了不正确的 @GetMapping?
在这里你可以看到我通过hateoas拉入的spring-boot-starter-web的版本:
[INFO] +- org.springframework.boot:spring-boot-starter-hateoas:jar:2.1.9.RELEASE:compile
[信息] | +- org.springframework.boot:spring-boot-starter-web:jar:2.1.9.RELEASE:compile
[信息] | | - org.springframework.boot:spring-boot-starter-tomcat:jar:2.1.9.RELEASE:compile
[信息] | | +- org.apache.tomcat.embed:tomcat-embed-core:jar:9.0.26:compile
[信息] | | - org.apache.tomcat.embed:tomcat-embed-websocket:jar:9.0.26:compile
[信息] | +- org.springframework.hateoas:spring-hateoas:jar:0.25.2.RELEASE:compile
[信息] | - org.springframework.plugin:spring-plugin-core:jar:1.2.0.RELEASE:compile
我已经启用了 Spring Actuator 的 mappings 端点,我什至可以看到被忽略的端点可用:
{
"handler": "public org.springframework.hateoas.Resources<com.example.Car> com.example.CarController.getCars(java.lang.String)",
"predicate": "{GET /api/{brand}, produces [application/hal+json]}",
"details": {
"handlerMethod": {
"className": "com.example.CarController",
"name": "getCars",
"descriptor": "(Ljava/lang/String;)Lorg/springframework/hateoas/Resources;"
},
"requestMappingConditions": {
"consumes": [],
"headers": [],
"methods": [
"GET"
],
"params": [],
"patterns": [
"/api/{brand}"
],
"produces": [
{
"mediaType": "application/hal+json",
"negated": false
}
]
}
}
}
编辑我添加了一个interceptor,让我可以看到handlerMethod 的目标是什么。
handlerMethod 是正确的:
public org.springframework.hateoas.Resources com.example.CarController.getCars(java.lang.String)
但我仍然收到以下错误:
内部服务器错误:缺少字符串类型方法参数的 URI 模板变量“模型”
我无法理解handlerMethod 不期望model 参数这一事实,但spring 仍然因此而引发错误。
【问题讨论】:
标签: java spring spring-restcontroller request-mapping get-mapping