WebMvcConfigurerAdapter已过时,使用WebMvcConfigurationSupport或者WebMvcConfigurer来代替
WebMvcConfigurerAdapter已经过时,在新版本2.x中被废弃,原因是springboot2.0以后,引用的是spring5.0,而spring5.0取消了WebMvcConfigurerAdapter
以下WebMvcConfigurerAdapter 比较常用的重写接口
/** 解决跨域问题 **/ public void addCorsMappings(CorsRegistry registry) ; /** 添加拦截器 **/ void addInterceptors(InterceptorRegistry registry); /** 这里配置视图解析器 **/ void configureViewResolvers(ViewResolverRegistry registry); /** 配置内容裁决的一些选项 **/ void configureContentNegotiation(ContentNegotiationConfigurer configurer); /** 视图跳转控制器 **/ void addViewControllers(ViewControllerRegistry registry); /** 静态资源处理 **/ void addResourceHandlers(ResourceHandlerRegistry registry); /** 默认静态资源处理器 **/ void configureDefaultServletHandling(DefaultServletHandlerConfigurer configurer);
新的版本解决方案目前有两种
方案1 直接实现WebMvcConfigurer (推荐)
* <p>{@code @EnableWebMvc}-annotated configuration classes may implement
* this interface to be called back and given a chance to customize the
* default configuration. --默认配置
@Configuration public class MyWebMvcConfg implements WebMvcConfigurer { @Override public void addViewControllers(ViewControllerRegistry registry) { registry.addViewController("/index").setViewName("index"); } }
方案2 直接继承WebMvcConfigurationSupport
继承WebMvcConfigurationSupport类,在扩展的类中重写父类的方法即可,但这种方式会有问题的,这种方式会屏蔽Spring Boot的@EnableAutoConfiguration中的设置。这时候启动项目时会发现映射根本没有加载成功,读取不到静态的资源也就是说application.properties中添加配置的映射配置没有起作用,然后我们会想到重写来进行重新映射
@Configuration public class MyMvcConfig extends WebMvcConfigurationSupport{ @Bean public WebMvcConfigurationSupport webMvcConfigurationSupport(){ WebMvcConfigurationSupport support = new WebMvcConfigurationSupport(){ @Override protected void addViewControllers(ViewControllerRegistry registry) { registry.addViewController("/").setViewName("login"); registry.addViewController("/main.html").setViewName("dashboard"); // registry.addViewController("/login.html").setViewName("login"); } @Override public void addResourceHandlers(ResourceHandlerRegistry registry) { //registry.addResourceHandler("/resources/static/**").addResourceLocations("classpath:/static/"); registry.addResourceHandler("/static/**").addResourceLocations("classpath:/resources/static/"); super.addResourceHandlers(registry); } }; return support; }
或是
@Configuration public class MyMvcConfig extends WebMvcConfigurationSupport { @Override protected void addViewControllers(ViewControllerRegistry registry) { registry.addViewController("/").setViewName("login"); registry.addViewController("/main.html").setViewName("dashboard"); // registry.addViewController("/login.html").setViewName("login"); } }