SpringBoot2.0 WebMvcConfigurerAdapter方法过时(踩坑)使用WebMvcConfigurationSupport或者WebMvcConfigurer来代替

在springboot2.0之前 我们都是 继承 WebMvcConfigurerAdapter 来实现url的定向,在springboot 2.0以后 WebMvcConfigurerAdapter 这个方法已经过时,那怎么来修改呢?

(1)改成继承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");
        }

}
推荐使用这种方法
(2)实现WebMvcConfigurer这个接口

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

你可能感兴趣的:(SpringBoot2.0 WebMvcConfigurerAdapter方法过时(踩坑)使用WebMvcConfigurationSupport或者WebMvcConfigurer来代替)