首页 > 编程 > Java > 正文

SpringBoot的拦截器中依赖注入为null的解决方法

2019-11-26 09:52:39
字体:
来源:转载
供稿:网友

该项目是基于SpringBoot框架的Maven项目。

今天在拦截器中处理拦截逻辑时需要使用注解调用其他方法 并且要从配置文件中读取参数。所以我使用了以下注解:

  @Reference  CoreRedisService redisService;  @Value("${channel}")  private String channel;  @Value("${allowMethod}")  private String allowMethod;

一个是获取接口的引用,两外两个是获取配置文件中的参数,

但是在debug过程中发现三个都没有注入进来出现了下图所示的情况:

 

可以看到三个值都为null。

然后我查看了我项目的配置,确定该拦截器的位置是否在注解的范围内。发现没问题, 百度了一下,发现了有个问题:拦截器加载的时间点在springcontext之前,所以在拦截器中注入自然为null

根据解决方法在配置拦截器链的类中先注入这个拦截器,代码如下:

package com.***;import org.springframework.context.annotation.Bean;import org.springframework.context.annotation.Configuration;import org.springframework.web.servlet.config.annotation.InterceptorRegistry;import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;/** * 配置拦截器链 * Created by yefuliang on 2017/10/23. */@Configurationpublic class bgqWebAppConfigurer extends WebMvcConfigurerAdapter {  @Bean  public bgqCommonInterceptorl bgqCommonInterceptorl() {    return new bgqCommonInterceptorl();  }  public void addInterceptors(InterceptorRegistry registry) {    // 多个拦截器组成一个拦截器链    // addPathPatterns 用于添加拦截规则    // excludePathPatterns 用户排除拦截    registry.addInterceptor(bgqCommonInterceptorl()).addPathPatterns("/**");    super.addInterceptors(registry);  }}

注意注入的是拦截器类,不是你拦截器里面要注入的类,然后拦截器链的 registry.addInterceptor(bgqCommonInterceptorl()).addPathPatterns(“/**”);

里面的第一个参数就不需要你再重新new一个了。

改好之后debug:

 

可以看到,都注入了进来,问题解决。

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

发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表