我正在尝试使用两个保存方法创建一个rest控制器。一种用于保存单个实体,另一种用于保存实体列表。
@RequestMapping(method = [POST, PUT])
fun save(@RequestBody entity: T): T {
return service.save(entity)
}
@RequestMapping(method = [POST, PUT])
fun save(@RequestBody entities: List<T>): List<T> {
return service.save(entities)
}
但是,由于我的假设是,类型擦除弹簧会引发以下异常。
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 'crudControllerImpl' method
public final T dk.fitfit.send.mail.CrudController.save(T)
to {[/messages],methods=[POST || PUT]}: There is already 'crudControllerImpl' bean method
public final java.util.List<T> dk.fitfit.send.mail.CrudController.save2(java.util.List<? extends T>) mapped.
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1694) ~[spring-beans-5.0.10.RELEASE.jar:5.0.10.RELEASE]
...
有任何线索吗?
答案 0 :(得分:0)
这是因为您具有相同的请求映射。 Spring不能基于请求有效负载来区分请求-仅基于方法,路径和标头。 您可以尝试从此处应用建议:Jackson mapping Object or list of Object depending on json input
对于您的情况,它看起来像
@RequestMapping(method = [POST, PUT])
fun save(@RequestBody @JsonFormat(with = JsonFormat.Feature.ACCEPT_SINGLE_VALUE_AS_ARRAY) entities: List<T>): List<T> {
return service.save(entities)
}