0

I'm trying to create a rest controller with two save methods. One for saving a single entity and one for saving a list of entities.

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

However due to, what I assume is, type erasure spring throws the following exception.

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]
...

Any clue?

user672009
  • 4,379
  • 8
  • 44
  • 77

1 Answers1

0

It's because you have identical request mappings. Spring can't distinguish requests based on request payload - only on method, path and headers. You can try to apply the suggestion from here: Jackson mapping Object or list of Object depending on json input

For your case, it'll look like

@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)
}
Alex
  • 7,460
  • 2
  • 40
  • 51