我正在尝试在 Spring Boot 中创建一个端点,它接受单个对象或这些对象的数组。我知道映射需要有唯一的签名,所以我想知道使用 POJO 使其工作的正确方法是什么?
@RequestMapping(method = { RequestMethod.POST })
public ResponseEntity<String> postSingleFoo(HttpServletRequest request,
@RequestBody(required = true) Foo foo) {
// process
}
@RequestMapping(method = { RequestMethod.POST })
public ResponseEntity<String> postMultiFoo(HttpServletRequest request,
@RequestBody(required = true) Foo[] foo) {
// process
}
显然,我遇到了不明确映射的异常。但我仍然想在我的 @RequestBody
注释中使用 POJO,因为我在其中执行了几次转换。
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'requestMappingHandlerMapping' defined in class path resource [org/springframework/boot/autoconfigure/web/WebMvcAutoConfiguration$EnableWebMvcConfiguration.class]: Invocation of init method failed; nested exception is java.lang.IllegalStateException: Ambiguous mapping. Cannot map 'fooController' method
public void com.usquared.icecream.lrs.controller.FooController.postSingleFoo(javax.servlet.http.HttpServletRequest,java.lang.String)
to {[/foo],methods=[POST]}: There is already 'fooController' bean method
正确实现此类功能的推荐方法是什么?
最佳答案
这不是一个可以通过 Spring MVC 解决的问题。 Spring MVC 从 @RequestMapping 注释处理程序方法创建映射。这些有助于区分 Spring MVC 如何委托(delegate)您的方法处理 HTTP 请求。您当前的配置尝试将两个处理程序方法映射到相同的请求详细信息。这永远行不通。
假设您需要 JSON 并与 Jackson 合作,一种解决方案是将您的 ObjectMapper
配置为 accept single values as arrays并使用数组参数定义单个处理程序方法。例如,您只需保留此处理程序方法
@RequestMapping(method = { RequestMethod.POST })
public ResponseEntity<String> postMultiFoo(HttpServletRequest request,
@RequestBody(required = true) Foo[] foo) {
// process
}
但要这样配置您的ObjectMapper
ObjectMapper mapper = new ObjectMapper();
mapper.configure(DeserializationFeature.ACCEPT_SINGLE_VALUE_AS_ARRAY, true);
配置取决于您的应用程序的配置方式。使用 Spring Boot,它应该像为 ObjectMapper
声明一个 @Bean
方法一样简单。对于典型的 Spring MVC 应用程序,您需要使用自定义 ObjectMapper
注册 MappingJackson2HttpMessageConverter
。
如果您的 JSON(请求正文)包含
{
"someProperty":"whatever"
}
Jackson 能够将单个值包装到 Foo[]
中,Spring MVC 会将其作为参数传递给您的处理程序方法。然后您可以检查数组的长度并采取相应的操作。
关于java - 使用 RequestBody 注释时的映射不明确,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42980022/