SpringBoot2.0如何自定义WebMvc配置

在Spring boot中如果引入Web模块后会进行自动配置,自动配置类为:org.springframework.boot.autoconfigure.web.servlet.WebMvcAutoConfiguration
如果自动配置满足不了我们的需求就需要我们进行自定义配置。
在Spring Boot1.0中我们可以通过继承WebMvcConfigurerAdapter这个适配类进行自定义配置

@Configuration
public class MyMvcConfig extends WebMvcConfigurerAdapter {

而在Spring Boot2.0中我们发现WebMvcConfigurerAdapter这个类并不建议使用
在这里插入图片描述
所以我们在Spring Boot2.0中如何进行拓展Mvc配置呢?

方法一:继承WebMvcConfigurationSupport
WebMvcConfigurationSupport中,有很多add方法提供给我们进行重写,拓展Mvc配置,包括添加拦截器,视图解析器等等。

protected void addInterceptors(InterceptorRegistry registry) {
    }

    protected PathMatchConfigurer getPathMatchConfigurer() {
        if (this.pathMatchConfigurer == null) {
            this.pathMatchConfigurer = new PathMatchConfigurer();
            this.configurePathMatch(this.pathMatchConfigurer);
        }

        return this.pathMatchConfigurer;
    }

    protected void configurePathMatch(PathMatchConfigurer configurer) {
    }

但存在的问题是当向容器中添加WebMvcConfigurationSupport这个Bean之后,将会全面接管MVC配置,导致Spring Boot的Mvc自动配置不生效,这显然是我们不想看到的。

为什么会导致这样的结果呢,我们可以看一下Spring Boot2.0启动Mvc自动配置的源码。

@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 {

在‘@ConditionalOnMissingBean(WebMvcConfigurationSupport.class)’这个注解中会检查容器中是否存在WebMvcConfigurationSupport,如果存在将不会启动Mvc自动配置。

所以如果我们的能够全面接管Mvc配置,进行重写可以采用这种方式。

方法二:实现WebMvcConfigurer接口
当我们进入WebMvcConfigurerAdapter这个类中我们会发现他实现了WebMvcConfigurer这个接口,那么我们就不需要继承,直接实现这个接口就好了,而在WebMvcConfigurer中许多方法都是被default修饰的,这样我们就可以选择自己需要的方法进行重写,从而达到拓展Mvc配置的目的。

/**
 * 自定义Mvc配置
 */
@Configuration
public class MyMvcConfig implements WebMvcConfigurer {

    /**
     * 注册拦截器
     * @param registry
     */
    @Override
    public void addInterceptors(InterceptorRegistry registry) {

        // 静态资源放行
        List<String> excludePathPatterns = new ArrayList<>();
        excludePathPatterns.add("/asserts/css/**");
        excludePathPatterns.add("/webjars/**");
        excludePathPatterns.add("/asserts/js/**");
        excludePathPatterns.add("/index.html");
        excludePathPatterns.add("/user/login");
        excludePathPatterns.add("/");

        // 注册拦截器
        registry.addInterceptor(new LoginHandleInterceptor())
                .addPathPatterns("/**")
                .excludePathPatterns(excludePathPatterns);
    }
}

非常的方便!!!

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值