WebMvcConfigurerAdapter过时及静态资源无效

在Springboot 2.0(Spring5)后用自己的的配置类继承WebMvcConfigurerAdapter时,idea提示这个类已经过时了.
网上很多说法会说使用WebMvcConfigurationSupport来代替,
然而如果使用WebMvcConfigurationSupport会导致Springboot的webmvc配置失效,即访问不到静态资源。这是因为WebMvc的自动配置都在WebMvcAutoConfiguration
类中,但是类中有这个注解@ConditionalOnMissingBean({WebMvcConfigurationSupport.class}),意思是一旦在容器中检测到WebMvcConfigurationSupport这个类,
WebMvcAutoConfiguration类中的配置都不生效,代码如下

@Configuration
@ConditionalOnWebApplication(type = Type.SERVLET)
@ConditionalOnClass({ Servlet.class, DispatcherServlet.class, WebMvcConfigurer.class })
@ConditionalOnMissingBean(WebMvcConfigurationSupport.class)
@AutoConfigureOrder(Ordered.HIGHEST_PRECEDENCE + 10)
@AutoConfigureAfter({ DispatcherServletAutoConfiguration.class,
		ValidationAutoConfiguration.class })
public class WebMvcAutoConfiguration {
    
}

因此正确接管Springmvc的方式应该如下

@Configuration
public class MyMvcConfig  implements WebMvcConfigurer {
    @Override
    public void addViewControllers(ViewControllerRegistry registry) {
        registry.addViewController("/").setViewName("login");
    }
}

猜你喜欢

转载自blog.csdn.net/KevinDai007/article/details/84075637
今日推荐