如何在Interceptor中使用@Autowired
config类:
@Configuration
public class WebAdminInterceptorConfig implements WebMvcConfigurer {
@Override
public void addInterceptors(InterceptorRegistry registry) {
registry.addInterceptor(new WebAdminInterceptor())
.addPathPatterns("/**")
.excludePathPatterns("/static");
}
}
Interceptor类:
public class WebAdminInterceptor implements HandlerInterceptor {
@Autowired
private RedisService redisService;
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
}
@Override
public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
redisService.get("aaa"); //redisService为null
}
@Override
public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
}
}
问题描述:
在Interceptor中,自动注入的对象为null
解决方案:
修改Config类如下:
@Configuration
public class WebAdminInterceptorConfig implements WebMvcConfigurer {
@Bean
WebAdminInterceptor webAdminInterceptor(){
return new WebAdminInterceptor();
}
@Override
public void addInterceptors(InterceptorRegistry registry) {
registry.addInterceptor(webAdminInterceptor())
.addPathPatterns("/**")
.excludePathPatterns("/static");
}
}