Search code examples
javaspringrequest-mapping

Can I have two the same methods annotated with @RequestMapping with different headers?


I have Controller in which I have:

    @RequestMapping(value = SEARCH_BY_FILTERS_WITH_TYPE, method= {RequestMethod.GET, RequestMethod.POST}, headers = JSON)
    @Secured(Permissions.VIEW)
    @ResponseBody
    public AjaxJsonResponseBuilder searchForFiltersWithTypeJson(@RequestBody SearchFiltersWithTypeRequest request) {
        return search(request);
    }

    @RequestMapping(value = SEARCH_BY_FILTERS_WITH_TYPE, method= {RequestMethod.GET, RequestMethod.POST})
    @Secured(Permissions.VIEW)
    @ResponseBody
    public AjaxJsonResponseBuilder searchForFiltersWithType(SearchFiltersWithTypeRequest request) {
        return search(request);
    }

and I have an error while starting application:

org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping': Invocation of init method failed; nested exception is java.lang.IllegalStateException: Ambiguous mapping. Cannot map 'searchController' method 
search.controller.SearchController#searchForFiltersWithTypeRequest(SearchFiltersWithType)
to {[GET, POST] [/search/filters/type]}: There is already 'searchController' bean method
search.controller.SearchController#searchForFiltersWithTypeRequest(SearchFiltersWithTypeRequest) mapped.

Spring version: <spring.version>5.3.34</spring.version>


Solution

  • Yes, you can have two or more identical @RequestMapping methods with different headers. However, you need to explicitly specify different headers in each method. In your case, you specified a header only for the searchForFiltersWithTypeJson method, but did not specify a header for the searchForFiltersWithType method. Therefore, Spring cannot determine which method should handle requests with a JSON header. Specify a header for the second method that is different from the first one to get rid of the error.