SpringBoot 解决拦截器注入Service 为空问题

  最近忙着做爬虫方面系统的开发,已经有一段时间没有更博了。过程中,一些踩过的坑也没有及时截图做总结,只能直接贴解决方案了。

一、自定义拦截器实现HandlerInterceptor接口

/**
 * 
 * Created by zhh on 2018/04/20.
 */
public class MyInterceptor implements HandlerInterceptor {

    @Autowired
    private NetworkProxyInfoService networkProxyInfoService;

    @Override
    public void afterCompletion(HttpServletRequest arg0, HttpServletResponse arg1, Object arg2, Exception arg3)
            throws Exception {
        // TODO Auto-generated method stub
    }

    @Override
    public void postHandle(HttpServletRequest arg0, HttpServletResponse arg1, Object arg2, ModelAndView arg3)
            throws Exception {
        networkProxyInfoService.getAllNetworkProxyInfoByIsValid(GobalConstant.ProxyValid.VALID);
    }

    @Override
    public boolean preHandle(HttpServletRequest arg0, HttpServletResponse arg1, Object arg2) throws Exception {
        // TODO Auto-generated method stub
        return true;
    }

}

二、自定义拦截器配置

/**
 * 
 * Created by zhh on 2018/04/20.
 */
@Configuration
public class MyWebMvcConfig extends WebMvcConfigurerAdapter {

    /**
     * 将自定义拦截器作为Bean写入配置
     * @return
     */
    @Bean
    public MyInterceptor myInterceptor() {
        return new MyInterceptor();
    }

    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        /**
         * 多个拦截器组成一个拦截器链
         * addPathPatterns 用于添加拦截规则
         * excludePathPatterns 用户排除拦截
         */
        registry.addInterceptor(myInterceptor()).addPathPatterns("/**");
        super.addInterceptors(registry);
    }

}

猜你喜欢

转载自blog.csdn.net/Dh_Chao/article/details/80016110