SpringBoot的拦截器中依赖注入为null的解决方法
该项目是基于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:
可以看到,都注入了进来,问题解决。
栏 目:JAVA代码
下一篇:Java使用Jdbc连接Oracle执行简单查询操作示例
本文标题:SpringBoot的拦截器中依赖注入为null的解决方法
本文地址:http://www.codeinn.net/misctech/136996.html


阅读排行
- 1Java Swing组件BoxLayout布局用法示例
- 2java中-jar 与nohup的对比
- 3Java邮件发送程序(可以同时发给多个地址、可以带附件)
- 4Caused by: java.lang.ClassNotFoundException: org.objectweb.asm.Type异常
- 5Java中自定义异常详解及实例代码
- 6深入理解Java中的克隆
- 7java读取excel文件的两种方法
- 8解析SpringSecurity+JWT认证流程实现
- 9spring boot里增加表单验证hibernate-validator并在freemarker模板里显示错误信息(推荐)
- 10深入解析java虚拟机




