Springboot 拦截器(HandlerInterceptorAdapter)中注入无效

1,传统filter和HandlerInterceptorAdapter的区别

springboot对传统Filter进行增强,添加更多细粒度的操作,分别实现预处理、后处理(调用了Service并返回ModelAndView,但未进行页面渲染)、返回处理(已经渲染了页面)
在preHandle(预处理)中,可以进行编码、安全控制等处理;
在postHandle(后处理)中,有机会修改ModelAndView;
在afterCompletion(返回处理)中,可以根据ex是否为null判断是否发生了异常,进行日志记录。
总之,传统的filter可以完成的功能,HandlerInterceptorAdapter都以完成。更详细信息可以查看HandlerInterceptorAdapter源码。

2,HandlerInterceptorAdapter的子类中,注入无效问题。

正确的步骤如下:
2.1,写一个类,继承HandlerInterceptorAdapter(抽象类),并重写响应的方法。
@SuppressWarnings("ALL")
@Component
public class GlobalInterceptor extends HandlerInterceptorAdapter {
@Autowired
UserService userService ;
@Override
public boolean preHandle(HttpServletRequest request , HttpServletResponse response , Object handler)
throws Exception {
userService.dosomething();
return super.preHandle(request , response , handler);
}

2.2,将该类在启动的时候,通过注解(@Component)交给spring托管,
2.3,在WebMvcConfigurerAdapter类的子类中的
@Autowired
private GlobalInterceptor globalInterceptor;
public static void main(String[] args) {
SpringApplication.run(TaxiApplication.class , args);
}
@Override
public void addInterceptors(InterceptorRegistry registry) {
registry.addInterceptor(globalInterceptor);
},注册即可。

上面主要做的事情就是,1,继承HandlerInterceptorAdapter,2,继承WebMvcConfigurerAdapter并注册拦截器,这里注册的时候,HandlerInterceptorAdapter子类必须是交给spring托管后的子类。

你可能感兴趣的:(Springboot 拦截器(HandlerInterceptorAdapter)中注入无效)