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
    ReportLogEntityMapper logService;
    private long start = System.currentTimeMillis();

    @Override
    public boolean preHandle(HttpServletRequest httpServletRequest, HttpServletResponse response, Object handler) throws Exception {
        start = System.currentTimeMillis();
        return super.preHandle(httpServletRequest, response, handler);
    }

    //存储查询消耗时间,以后优化代码时查询
    @Override
    public void postHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, ModelAndView modelAndView) throws Exception {
        ReportLogEntity logEntity = new ReportLogEntity();
        logEntity.setCostTime((System.currentTimeMillis() - start));
        logEntity.setRequestUrl(new String(httpServletRequest.getRequestURL()));
        logEntity.setRequestUri(httpServletRequest.getRequestURI());
        logEntity.setQueryString(httpServletRequest.getQueryString());
        logEntity.setRemoteAddr(httpServletRequest.getRemoteAddr());
        logEntity.setCreatedDate(new Date());
        logService.insertSelective(logEntity);
    }

2.2,将该类在启动的时候,通过注解(@Component)交给spring托管,

2.3,在WebMvcConfigurerAdapter类的子类中的
@Configuration
public class InterceptorConfig extends WebMvcConfigurerAdapter {
    @Autowired
    private GlobalInterceptor globalInterceptor;

    public static void main(String[] args) {
        SpringApplication.run(SuperrescueReportingApplication.class, args);
    }

    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        registry.addInterceptor(new ReportInterceptor()).addPathPatterns("/**");
        registry.addInterceptor(globalInterceptor);
        super.addInterceptors(registry);
    }
}

注册即可。

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

装载自:https://www.jianshu.com/p/33a69534ea08

原文地址:https://www.cnblogs.com/huanghuanghui/p/10283065.html