通過返回WebMvcConfigurationSupport 的方式, 默認會覆蓋 Spring boot的自動配置, 導致配置失效靜態資源無法訪問:但是在WebMvcConfigurationadpter(已久過時)這是允許的
@Bean public WebMvcConfigurationSupport initIndexConfig() { return new WebMvcConfigurationSupport() { @Override protected void addViewControllers(ViewControllerRegistry registry) { registry.addViewController("/").setViewName("login"); registry.addViewController("/index.html").setViewName("login"); } @Override protected void addResourceHandlers(ResourceHandlerRegistry registry) { registry.addResourceHandler("/**") .addResourceLocations("classpath:/resources") .addResourceLocations("classpath:/static") .addResourceLocations("classpath:/templates") .addResourceLocations("classpath:/public"); } @Override protected void addInterceptors(InterceptorRegistry registry) { super.addInterceptors(registry); } }; }
WebMvcConfigurerAdapter 是一個適配器類,
/** @deprecated */ @Deprecated public abstract class WebMvcConfigurerAdapter implements WebMvcConfigurer { public WebMvcConfigurerAdapter() { }
而WebMvcConfigurationSupport 提供默認實現 不是一個空方法
public class WebMvcConfigurationSupport implements ApplicationContextAware, ServletContextAware { private static final boolean romePresent; private static final boolean jaxb2Present; private static final boolean jackson2Present; private static final boolean jackson2XmlPresent; private static final boolean jackson2SmilePresent; private static final boolean jackson2CborPresent;
所以: 采用返回 @Bean的方式, 會覆蓋實現的很多默認配置導致不能使用,
正確的使用方法是:
@Configuration public class AppConfig extends WebMvcConfigurationSupport{ @Override protected void addViewControllers(ViewControllerRegistry registry) { registry.addViewController("/").setViewName("login"); registry.addViewController("/index.html").setViewName("login"); } @Override protected void addResourceHandlers(ResourceHandlerRegistry registry) { registry.addResourceHandler("/**") .addResourceLocations("classpath:/resources") .addResourceLocations("classpath:/static") .addResourceLocations("classpath:/templates") .addResourceLocations("classpath:/public"); } @Override protected void addInterceptors(InterceptorRegistry registry) { super.addInterceptors(registry); }
你還可以選擇 直接實現
WebMvcConfigurer;
關於支持Webjar Swagger 等Jar包的資源路徑
/** * 資源路徑 映射 */ @Override protected void addResourceHandlers(ResourceHandlerRegistry registry) { registry.addResourceHandler("/**") .addResourceLocations("classpath:/resources") .addResourceLocations("classpath:/static") .addResourceLocations("classpath:/templates") .addResourceLocations("classpath:/public"); /** * 支持webjars */ registry.addResourceHandler("/webjars/**") .addResourceLocations("classpath:/META-INF/resources/webjars/"); /** * 支持swagger */ registry.addResourceHandler("swagger-ui.html") .addResourceLocations("classpath:/META-INF/resources/"); super.addResourceHandlers(registry); }