为什么 @GetMapping 和 @PostMapping 对相同的 URI 抛出错误?

Why @GetMapping & @PostMapping throw error for same URI?

Option-1: Worke fine

@RequestMapping(value = "myuri/" ,method = RequestMethod.GET)
 MyResponse myMethod1(@RequestBody MyRequest myRequest) {
   // Code
 }

@RequestMapping(value = "myuri/" ,method = RequestMethod.POST)
 MyResponse myMethod2(@RequestBody MyRequest myRequest) {
   // Code
 }

Option-2: Doesn't work

@GetMapping
@RequestMapping(value = "myuri/" )
MyResponse myMethod1(@RequestBody MyRequest myRequest) {

    return null;
}

@PostMapping
@RequestMapping(value = "myuri/")
MyResponse myMethod2(@RequestBody MyRequest myRequest) {
    return null;
}

Why option-2 throws an exception

java.lang.IllegalStateException: Ambiguous mapping.

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。

  1. @RequestMapping(value = "myuri/" ,method = RequestMethod.GET) 这将导致 myuri 上的 GET 请求映射到 myMethod1.

  2. @RequestMapping(value = "myuri/" ,method = RequestMethod.POST) 这将导致 myuri 上的 POST 请求映射到 myMethod2.

您的第二个示例将 2 个方法映射到 2 个 URLs,其中既有不同的方法也有相同的方法。

  1. @RequestMapping(value = "myuri/") 这将导致 myuri 上的 ANY 请求映射到 myMethod1.
  2. @GetMapping 这将导致 / 上的 GET 请求转到 myMethod1
  3. @RequestMapping(value = "myuri/") 这将导致 myuri 上的 ANY 请求映射到 myMethod2.
  4. @PostMapping 这将导致 / 上的 POST 请求转到 myMethod1

因为 1 和 3 是相同的映射到不同的方法 Spring 无法区分并引发错误。

这可能是因为您误解了 @GetMapping and @PostMapping 注释以及如何使用它们。这些映射分别是 @RequestMapping(method=GET)@RequestMapping(method=POST) 的快捷方式。在您的定义中保存相同的 space 并且它们非常清楚。

所以不用

@GetMapping
@RequestMapping(value = "myuri/" )

你应该只写 @GetMapping("myuri/") 来实现你想要的。在检测之后,这会转换为 myuri 上的 GET 请求的映射,以执行给定的方法。