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

软件发布|下载排行|最新软件

当前位置:首页IT学院IT技术

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

落_尘   2021-03-31 我要评论

该项目是基于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.
 */
@Configuration
public 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:

 

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

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

猜您喜欢

Copyright 2022 版权所有 软件发布 访问手机版

声明:所有软件和文章来自软件开发商或者作者 如有异议 请与本站联系 联系我们