1. Problem description
After the project is started, the injection under the interceptor is null, which affects the logical operation of the interceptor. As shown below:
Second, the solution strategy
Reason: Interceptor loading is completed before springcontext is created. For details, please refer to the relationship between spring's interceptor loading process and IOC
Solution 1 : Use @Bean to load the class before the interceptor is initialized. The focus is on @Bean's interceptor processing and the introduction of getCheckFilter()
details as follows:
// 拦截器处理
public class CheckFilter implements HandlerInterceptor {
@Autowired
private SystemService systemService;
}
// 配置类处理
@Configuration
public class WebMvcConfig extends WebMvcConfigurationSupport {
@Bean
public CheckFilter getCheckFilter(){
return new CheckFilter();
}
@Override
protected void addInterceptors(InterceptorRegistry registry) {
registry.addInterceptor(getCheckFilter()).addPathPatterns("/**").
excludePathPatterns("/admin/auth/**");
super.addInterceptors(registry);
}
@Override
protected void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler("/static/**").addResourceLocations("classpath:/static/");
super.addResourceHandlers(registry);
}
@Override
protected void configureViewResolvers(ViewResolverRegistry registry) {
registry.jsp("/WEB-INF/",".jsp");
super.configureViewResolvers(registry);
}
}
Solution 2 : Add configuration annotations such as @Configuration, @Component to the interceptor . Inject in the configuration class , the specific operations are as follows:
// 拦截器处理
@Configuration //或者 @Component
public class CheckFilter implements HandlerInterceptor {
@Autowired
private SystemService systemService;
}
// 配置类处理
@Configuration
public class WebMvcConfig extends WebMvcConfigurationSupport {
@Autowired
private CheckFilter checkFilter;
@Override
protected void addInterceptors(InterceptorRegistry registry) {
registry.addInterceptor(checkFilter).addPathPatterns("/**").
excludePathPatterns("/admin/auth/**");
super.addInterceptors(registry);
}
@Override
protected void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler("/static/**").addResourceLocations("classpath:/static/");
super.addResourceHandlers(registry);
}
@Override
protected void configureViewResolvers(ViewResolverRegistry registry) {
registry.jsp("/WEB-INF/",".jsp");
super.configureViewResolvers(registry);
}
}
Three, knowledge summary
1. Involving spring's interceptor loading process and IOC management
2. Reference materials https://blog.csdn.net/dengdeng333/article/details/87878882