在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);
}
}
非常的方便!!!