2016-11-30 27 views
3

我想在Windows中使用WebMvcConfigurerAdapter添加資源處理程序,但在Linux中不起作用,因此我添加了WebMvcConfigurationSupportWebMvcConfigurationSupport與WebMvcConfigurerAdapter混淆

經過調試和測試,我發現在兩個操作系統中都會創建兩個bean,但WebMvcConfigurerAdapter的覆蓋功能只會在Windows上執行,WebMvcConfigurationSupport的覆蓋功能只會在Linux上執行。

我找不到原因。兩個配置類如下所示:

@Configuration 
public class JxWebAppConfigurer extends WebMvcConfigurerAdapter { 
    @Override 
    public void addResourceHandlers(ResourceHandlerRegistry registry) { 
    registry.addResourceHandler("/**").addResourceLocations("file:"+System.getProperty("user.dir")+"/src/main/webapp/"); 
    super.addResourceHandlers(registry); 
    } 
} 

這是另一種:

@Configuration 
public class JxWebConfiguration extends WebMvcConfigurationSupport { 
    @Override 
    public void addResourceHandlers(ResourceHandlerRegistry registry) { 
     registry.addResourceHandler("/**").addResourceLocations("file:"+System.getProperty("user.dir")+"/src/main/webapp/"); 
     super.addResourceHandlers(registry); 
    } 
} 

@EnalbeMvc是已經在主類

回答

4

如前所述in the @EnableWebMvc Documentation加入:

將此註釋添加到@Configuration類中,將導入彈簧 MVC confi從WebMvcConfigurationSupport

guration

{..}

要定製導入的配置,實現接口 WebMvcConfigurer或更可能延伸的空的方法基類 WebMvcConfigurerAdapter並重寫個人方法

{..}

如果WebMvcConfigurer不公開,需要 進行配置一些高級設置,考慮刪除@EnableWebMvc註釋和 直接從WebMvcConfigurationSupport

延伸

所以在效果之一:

  1. @EnableWebMvc +擴展WebMvcConfigurerAdapter(建議第一個選項)
  2. 直接從WebMvcConfigurationSupport擴展(完全控制的備用選擇)

(上需要@Configuration這兩種情況下)

+0

好的,我昨天晚上讀了文檔並再次測試,發現另一個@EnableWebMvc,我以前沒有找到,這是問題,一個@@ EnableWebMvc就足夠了,但我添加了幾個,並忽略它。 – ysjiang

+0

如果您發現該回答有用,請考慮upvoting /接受它。 – dimitrisli

+0

我還有一個問題:我可以擴展WebMvcConfigurationSupport(或DelegatingWebMvcConfiguration,它們之間有什麼區別?)並仍然使用WebAutoConfiguration?或者還有另一種方法來添加資源處理程序,並且不要關閉WebAutoConfiguration?非常感謝〜 – ysjiang

0

我知道的原因。如上所述,您應該選擇一個選項(延伸至WebMvcC[email protected]或僅延伸至WebMvcConfigurationSupport);

切勿使用@EnableWebMvc和擴展WebMvcConfigurationSupport 在一起!

如果使用彈簧啓動的@EnableAutoConfiguration,你可以擴展WebMvcConfigurerAdapter,並且不使用@EnableMvc

0

org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter的替代解決方案是org.springframework.web.servlet.config.annotation.WebMvcConfigurationSupport(我使用Spring框架5.0.2.RELEASE)。

WebMvcConfigurerAdapter已被棄用。