【MARK】拦截器中自动注入失败问题
我在拦截器中想自动注入一个对象的时候发现无法注入,获取到的一直是null
public class RestInterceptor implements HandlerInterceptor {
@Autowired
private EscUserMapper escUserMapper;
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws BaseAppException {
return true;
}
@Override
public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler,
ModelAndView modelAndView) throws BaseAppException {
// TODO Auto-generated method stub
}
@Override
public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex)
throws BaseAppException {
// TODO Auto-generated method stub
}
}
解决办法:
在Spring添加拦截器之前先自己创建一下这个Spring Bean,这样就能在Spring映射这个拦截器前自动注入对象了。
@Configuration public class RestWebAppConfigurer extends WebMvcConfigurerAdapter { @Bean public RestInterceptor restInterceptor() { return new RestInterceptor(); } public void addInterceptors(InterceptorRegistry registry) { registry.addInterceptor(restInterceptor()).addPathPatterns("/iot/**"); super.addInterceptors(registry); } }
参考文档:http://www.cnblogs.com/niceboat/p/6958895.html