我正在嘗試多載@RestController具有相同端點(url)的類的方法。但是,當我這樣做時,我收到以下錯誤:
在類路徑資源 [org/springframework/boot/autoconfigure/web/servlet/WebMvcAutoConfiguration$EnableWebMvcConfiguration.class] 中創建名稱為“requestMappingHandlerMapping”的 bean 時出錯:呼叫 init 方法失敗;嵌套例外是 java.lang.IllegalStateException: Ambiguous mapping。無法將 'helloWorldController' 方法 com.rest.webservices.restfulwebservices.helloworld.HelloWorldController#helloWorldInternationalized(Locale) 映射到 {GET [/hello-world-internationalized]}:已經有 'helloWorldController' bean 方法
如果我將端點(url)更改為其他內容,錯誤就會消失。在下面的代碼中,您可以看到我使用"hello-world-internationalized"字串作為兩種方法的端點值,這給了我關于 bean 方法的錯誤。
@RestController
public class HelloWorldController {
@Autowired
private MessageSource messageSource;
@GetMapping(path="/hello-world-internationalized")
public String helloWorldInternationalized(@RequestHeader(name="Accept-Language", required=false) Locale locale) {
return messageSource.getMessage("good.morning.message", null, locale);
}
//other version of the method
@GetMapping(path="/hello-world-internationalized")
public String helloWorldInternationalizedVersion2() {
return messageSource.getMessage("good.morning.message", null, LocaleContextHolder.getLocale());
}
}
在 Spring Boot@RestController類中,是否不能多載一個方法并為兩者使用相同的 url?
我會很感激任何評論。您的評論將幫助我更好地理解這種情況。
謝謝你。
uj5u.com熱心網友回復:
是和不是。您目前擁有的是映射到同一個 URL 的 2 個 get 方法,Spring 的映射中沒有區分器來確定當請求進入時使用哪一個。
當您在第二個請求標頭中使用請求標頭時,您可以使用 上的headers元素@GetMapping添加額外的映射資訊。
@GetMapping(path="/hello-world-internationalized", headers="Accept-Language")
現在,如果存在該特定標頭,則現在將呼叫該方法。
重要的是,每個方法的映射資訊(或元資料)必須是唯一的,如果資訊相同,您將收到錯誤訊息。
uj5u.com熱心網友回復:
你不能那樣做。
spring mvc中web框架和spring ioc的集成是通過ContextLoaderListener監聽servlet背景關系的創建,然后加載父容器來完成的。然后通過配置一個servlet物件DispatcherServlet,在DispatcherServlet初始化的時候加載具體的子容器。
所以,不能用同一個url實作多載。
您可以在 Service 中實作多載。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qianduan/417595.html
標籤:
