Search code examples
spring-mvcgenericsjava-8request-mapping

@RequestMapping & Bound Generic Paramters


The following @RequestMapping's produce an ambiguous request mapping for a @RestController in Spring Boot 1.5/Java 8.

Is there a way to 'negate' the generic constraint on the fist method to not include Iterable's? I would prefer to keep the same method name, path etc.. (i.e.) A post with an array would go to one method, and a post of a single item would go to the second method.

@RequestMapping(method = RequestMethod.POST, value="/foo")
public T save(T item){
    ...
}
@RequestMapping(method = RequestMethod.POST, value="/foo")
public Iterable<T> save(Iterable<T> items){
    ...
}

Solution

  • Your mapping is obviously ambiguous.

    You need to specify a different endpoint for each saved type, or you can narrow mapping via elements of @RequestMapping annotation.

    For example you could implement something like this:

    @RequestMapping(method = RequestMethod.POST, value="/foo", params="item")
    public T save(T item){
        ...
    }
    @RequestMapping(method = RequestMethod.POST, value="/foo", params="items")
    public Iterable<T> save(Iterable<T> items){
        ...
    }
    

    or, using headers:

    @RequestMapping(method = RequestMethod.POST, value="/foo", headers="Input-Type=item")
    public T save(T item){
        ...
    }
    @RequestMapping(method = RequestMethod.POST, value="/foo", headers="Input-Type=items")
    public Iterable<T> save(Iterable<T> items){
        ...
    }