java 如何在SpringBoot中使用不同类型的“@RequestBody”重载控制器API?

pdkcd3nj  于 2023-03-16  发布在  Java
关注(0)|答案(1)|浏览(144)

所有!我目前正在做一个新的项目与SpringBoot和以下是我目前遇到的问题。我想overload这个控制器与不同类型的参数。我该如何实现呢?

@RequestMapping(method = RequestMethod.POST, value = "/register")
    public Status registerConnection(@RequestBody Connection connection) throws Exception 
    {
        xxxx
    }
    @RequestMapping(method = RequestMethod.POST, value = "/register")
    public Status registerConnections(@RequestBody List<Connection> connections){ 
        xxxx
    }

目前,如果我运行该程序,它报告了一个错误,如下所示:

Caused by: java.lang.IllegalStateException: Ambiguous mapping. Cannot map 'connectionController' method 
com.comacnet.controller.ConnectionController#registerConnections(List)
to {POST [/connection/register]}: There is already 'connectionController' bean method
com.comacnet.controller.ConnectionController#registerConnection(Connection) mappe
bvn4nwqk

bvn4nwqk1#

应该为Map使用不同路径。
但是,如果你仍然希望做同样的下面的代码片段可能会有所帮助.

@RestController
@RequestMapping("/api")
public class MyController {

    @PostMapping("/myendpoint")
    public ResponseEntity<String> handleMyStringRequestBody(@RequestBody String requestBody) {
        return ResponseEntity.ok("This is String Body");
    }

    @PostMapping("/myendpoint")
    public ResponseEntity<String> handleMyJsonRequestBody(@RequestBody JsonObject requestBody) {
        return ResponseEntity.ok("This is JSON body");
    }
}

相关问题