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");
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值