spring - 冲突方法签名
问题描述
我正在尝试使用两种保存方法创建一个休息控制器。一个用于保存单个实体,一个用于保存实体列表。
@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 mapping Object or list of Object based 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)
}
推荐阅读
- javascript - 如何隐藏或删除输入字段外的内容?
- docker - 如何像本地一样访问mongodb
- javascript - 如何获得 CSS 位置:固定背景图像以正常工作?
- c++ - 在 C++ 线程中使用逗号和分号
- javascript - 如何在我的 Javascript 游戏中添加子弹
- javascript - 如果其参考状态已更新,如何最有效地更新父状态
- arrays - 有效地导航数组和选定的字符串
- debugging - GDB比较一个存在的字符和一个不存在的字符?
- google-apps-script - 您如何判断文本是否适合其边界形状?
- excel - Excel PowerQuery:如何将巨大的表格反透视或转置为可读格式以进行分析