选项1:正常工作
@RequestMapping(value = "myuri/" ,method = RequestMethod.GET)
MyResponse myMethod1(@RequestBody MyRequest myRequest) {
// Code
}
@RequestMapping(value = "myuri/" ,method = RequestMethod.POST)
MyResponse myMethod2(@RequestBody MyRequest myRequest) {
// Code
}
选项2:无效
@GetMapping
@RequestMapping(value = "myuri/" )
MyResponse myMethod1(@RequestBody MyRequest myRequest) {
return null;
}
@PostMapping
@RequestMapping(value = "myuri/")
MyResponse myMethod2(@RequestBody MyRequest myRequest) {
return null;
}
为什么选项2引发异常
java.lang.IllegalStateException:模糊的映射。
Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'requestMappingHandlerMapping' defined in class path resource [org/springframework/boot/autoconfigure/web/servlet/WebMvcAutoConfiguration$EnableWebMvcConfiguration.class]: Invocation of init method failed; nested exception is java.lang.IllegalStateException: Ambiguous mapping. Cannot map 'myRestController' method
com.a.b.c.service.model.MyResponse com.a.b.my.service.rest.myRestController.myMethod2(com.a.b.c.service.model.MyRequest)
to { /my/myuri/}: There is already 'myRestController' bean method
com.a.b.c.service.model.MyResponse com.a.b.my.service.rest.myRestController.myMethod1(com.a.b.c.service.model.MyRequest) mapped.
您的第一个示例将2种方法映射到具有不同post方法的单个URL。
[@RequestMapping(value = "myuri/" ,method = RequestMethod.GET)
这将导致对myuri
上的GET请求进行myMethod1
的映射。
[@RequestMapping(value = "myuri/" ,method = RequestMethod.POST)
这将导致对myuri
上的POST请求进行映射以转到myMethod2
。
您的第二个示例将2个方法映射到2个使用不同方法和相同方法的URL。
@RequestMapping(value = "myuri/")
这将导致对myuri
上的ANY请求去myMethod1
的映射。@GetMapping
,这将导致/
上的GET请求转到myMethod1
。 @RequestMapping(value = "myuri/")
这将导致对myuri
上的ANY请求去myMethod2
的映射。@PostMapping
,这将导致对/
的POST请求转到myMethod1
。 由于1和3是相同的映射,将用于不同的方法,Spring无法区分并引发错误。
这可能是由于您误解了@GetMapping
和@GetMapping
注释以及如何使用它们的事实。映射是@PostMapping
和@PostMapping
的快捷方式。为您的定义节省相同的空间,它们非常清楚。
所以代替
@RequestMapping(method=GET)
您应该只写@RequestMapping(method=POST)
以实现所需的功能。在检测到之后,这将转换为@GetMapping
@RequestMapping(value = "myuri/" )
上的GET请求的映射以执行给定的方法。