详解SpringBoot 解决拦截器注入Service为空问题
一、自定义拦截器实现HandlerInterceptor接口
/**
*
*Createdbyzhhon2018/04/20.
*/
publicclassMyInterceptorimplementsHandlerInterceptor{
@Autowired
privateNetworkProxyInfoServicenetworkProxyInfoService;
@Override
publicvoidafterCompletion(HttpServletRequestarg0,HttpServletResponsearg1,Objectarg2,Exceptionarg3)
throwsException{
//TODOAuto-generatedmethodstub
}
@Override
publicvoidpostHandle(HttpServletRequestarg0,HttpServletResponsearg1,Objectarg2,ModelAndViewarg3)
throwsException{
networkProxyInfoService.getAllNetworkProxyInfoByIsValid(GobalConstant.ProxyValid.VALID);
}
@Override
publicbooleanpreHandle(HttpServletRequestarg0,HttpServletResponsearg1,Objectarg2)throwsException{
//TODOAuto-generatedmethodstub
returntrue;
}
}
二、自定义拦截器配置
/**
*
*Createdbyzhhon2018/04/20.
*/
@Configuration
publicclassMyWebMvcConfigextendsWebMvcConfigurerAdapter{
/**
*将自定义拦截器作为Bean写入配置
*@return
*/
@Bean
publicMyInterceptormyInterceptor(){
returnnewMyInterceptor();
}
@Override
publicvoidaddInterceptors(InterceptorRegistryregistry){
/**
*多个拦截器组成一个拦截器链
*addPathPatterns用于添加拦截规则
*excludePathPatterns用户排除拦截
*/
registry.addInterceptor(myInterceptor()).addPathPatterns("/**");
super.addInterceptors(registry);
}
}
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持毛票票。