冲突方法签名



我正在尝试创建一个具有两种保存方法的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]
...

有线索吗?

这是因为您有相同的请求映射。Spring不能根据请求负载来区分请求,只能根据方法、路径和头来区分。您可以尝试应用这里的建议:Jackson映射对象或对象列表取决于json输入

对于您的情况,它看起来像

@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)
}

最新更新