网站建设资讯

NEWS

网站建设资讯

详解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);
 } 
}

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持创新互联。


名称栏目:详解SpringBoot解决拦截器注入Service为空问题
网站网址:http://cdweb.net/article/gdoehp.html