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

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM