我可以有两个相同的方法,用@RequestMapping注释并具有不同的标头吗?

问题描述 投票:0回答:1

我有控制器,其中有:

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

我在启动应用程序时遇到错误:

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>5.3.34</spring.version>

java spring request-mapping
1个回答
0
投票

是的,您可以拥有两个或多个具有不同标头的相同 @RequestMapping 方法。但是,您需要在每个方法中显式指定不同的标头。在您的例子中,您仅为

searchForFiltersWithTypeJson
方法指定了标头,但没有为
searchForFiltersWithType
方法指定标头。因此,Spring 无法确定使用哪种方法来处理带有 JSON 标头的请求。为第二个方法指定与第一个方法不同的标头以消除错误。

© www.soinside.com 2019 - 2024. All rights reserved.