SpringBoot solves the problem that the interceptor injection service is empty

  Recently, I have been busy with the development of crawler systems, and I have not updated my blog for a while. In the process, some of the pits that have been stepped on did not take screenshots to summarize in time, so the solution can only be directly posted.

First, the custom interceptor implements the HandlerInterceptor interface

/**
 * 
 * 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;
    }

}

Second, the custom interceptor configuration

/**
 * 
 * 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);
    }

}

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324618703&siteId=291194637