以下这种方式能注册拦截器,也能使用,但是获取到注入的service 是null。
我的拦截器类
@Component
public class LesionInterceptor implements HandlerInterceptor {
@Autowired
private IOrganizationService organizationService;
// TODO 其他代码
}
配置类
/**
* spring boot 2.0以上版本
* https://blog.csdn.net/qq_35706771/article/details/82957014
*
* @author Jmx
*/
@Configuration
public class MyWebMvcConfig implements WebMvcConfigurer {
@Bean
public MyWebMvcConfig getMyWebMvcConfig() {
MyWebMvcConfig myWebMvcConfig = new MyWebMvcConfig() {
@Override
public void addViewControllers(ViewControllerRegistry registry) {
// registry.addViewController("/").setViewName("alogin");
// registry.addViewController("/login").setViewName("alogin");
// registry.addViewController("/main.html").setViewName("dashboard");
}
// 注册拦截器
@Override
public void addInterceptors(InterceptorRegistry registry) {
registry.addInterceptor(new LesionInterceptor())
.addPathPatterns("/**")
.excludePathPatterns("/login", "/swagger", "/",
"/swagger-resources/**", "/webjars/**",
"/v2/**", "/swagger-ui.html/**");
super.addInterceptors(registry);
}
};
return myWebMvcConfig;
}
}
改进方式
/**
* spring boot 2.0以上版本
* https://blog.csdn.net/qq_35706771/article/details/82957014
*
* @author Jmx
*/
@Configuration
public class MyWebMvcConfig implements WebMvcConfigurer {
//这里的LesionInterceptor 是上面定义的拦截器的类型
@Bean
public LesionInterceptor MyWebMvcConfig() {
// MyWebMvcConfig myWebMvcConfig = new MyWebMvcConfig() {
// @Override
// public void addViewControllers(ViewControllerRegistry registry) {
// // registry.addViewController("/").setViewName("alogin");
// // registry.addViewController("/login").setViewName("alogin");
// // registry.addViewController("/main.html").setViewName("dashboard");
// }
//
// // 注册拦截器
// @Override
// public void addInterceptors(InterceptorRegistry registry) {
// registry.addInterceptor(new LesionInterceptor())
// .addPathPatterns("/**")
// .excludePathPatterns("/login", "/swagger", "/",
// "/swagger-resources/**", "/webjars/**",
// "/v2/**", "/swagger-ui.html/**");
// super.addInterceptors(registry);
// }
// };
return new LesionInterceptor();
}
@Override
public void addInterceptors(InterceptorRegistry registry) {
//多个拦截器组成一个拦截器链
// addPathPatterns用于添加拦截规则
// excludePathPatterns用户排除拦截
//对来自/** 全路径请求进行拦截
registry.addInterceptor(MyWebMvcConfig()).addPathPatterns("/**");
}
}
至此解决,
还有一种方式就是继承 WebMvcConfigurerAdapter,但是这种方式已经过时。可参考 https://blog.csdn.net/wmh13262227870/article/details/77005920