Fork me on GitHub

Spring Boot2.X 拦截器配置

Spring Boot2.0 之后的拦截器配置和之前不太一样,但是殊途同归,特此总结一下😝

Spring Boot2.0 之前

Spring Boot2.0 之前的拦截器配置如下:

1
2
3
4
5
6
7
8
9
10
11
12
@Configuration
public class InterceptorConfigurerAdapter extends WebMvcConfigurerAdapter {
@Bean
RestRequestValidatorInterceptor restRequestValidatorInterceptor() {
return new RestRequestValidatorInterceptor();
}
@Override
public void addInterceptors(InterceptorRegistry registry) {
registry.addInterceptor(restRequestValidatorInterceptor()).addPathPatterns("/**")
.excludePathPatterns("/push/test");
}
}

这是没问题的,但是在 Spring Boot2.0 或更高版本中,WebMvcConfigurerAdapter 类已经 deprecated:
image
虽然过期,但是可以看到 WebMvcConfigurerAdapter 实现了 WebMvcConfigurer 接口,所以可以直接自定义类实现 WebMvcConfigurer 接口,其他不变。

Spring Boot2.0 之后

只需要将之前继承的 WebMvcConfigurerAdapter 类改为实现 WebMvcConfigurer 接口。

1
2
3
4
5
6
7
8
9
10
11
12
@Configuration
public class InterceptorConfigurerAdapter implements WebMvcConfigurer {
@Bean
RestRequestValidatorInterceptor restRequestValidatorInterceptor() {
return new RestRequestValidatorInterceptor();
}
@Override
public void addInterceptors(InterceptorRegistry registry) {
registry.addInterceptor(restRequestValidatorInterceptor()).addPathPatterns("/**")
.excludePathPatterns("/push/test");
}
}

------本文结束------
0%