StringRedisTemplate Autowired注入为空解决

如下注入方式报空指针异常: java.lang.NullPointerException: null

java 复制代码
    @Autowired
    private StringRedisTemplate redisTemplate;

**解决办法:**查看该类上有没有加注解,如@Component等,没加的话加上。

还有一种是在工具类中使用,由于要在其他静态方法中使用,如下我注入的是静态变量,也加了类注解,还是报空指针异常。

java 复制代码
    @Autowired
    private static StringRedisTemplate redisTemplate;

解决办法: 使用Java提供的@PostConstruce注解,赋予静态对象redisTemplateStatic一个实例,代码如下,该方式不止作用于StringRedisTemplate ,其他第三方库静态属性均可。@PostConstruct该注解被用来修饰一个非静态的void()方法。PostConstruct在构造函数之后执行,init()方法之前执行。

执行顺序:

Constructor(构造方法) -> @Autowired(依赖注入) -> @PostConstruct(注释的方法)

java 复制代码
@Component
public class GlobalUtils {    

    private static StringRedisTemplate redisTemplateStatic;
    @Autowired
    private StringRedisTemplate redisTemplate;

    private static ObjectMapper objectMapper;
    @Autowired
    private ObjectMapper mapper;

    @PostConstruct
    public void initData() {
        objectMapper = this.mapper;
        redisTemplateStatic = this.redisTemplate;
    }
        
    // 可直接在其他静态方法中使用


}
相关推荐
Leo July3 小时前
【Java】Spring Security 6.x 全解析:从基础认证到企业级权限架构
java·spring·架构
星火开发设计4 小时前
C++ 数组:一维数组的定义、遍历与常见操作
java·开发语言·数据结构·c++·学习·数组·知识
码道功成4 小时前
Pycham及IntelliJ Idea常用插件
java·ide·intellij-idea
TTGGGFF4 小时前
控制系统建模仿真(一):掌握控制系统设计的 MAD 流程与 MATLAB 基础运算
开发语言·matlab
消失的旧时光-19434 小时前
第四篇(实战): 订单表索引设计实战:从慢 SQL 到毫秒级
java·数据库·sql
2501_944424124 小时前
Flutter for OpenHarmony游戏集合App实战之贪吃蛇食物生成
android·开发语言·flutter·游戏·harmonyos
それども5 小时前
@ModelAttribute vs @RequestBody
java
雨中飘荡的记忆5 小时前
深度详解Spring Context
java·spring
Tao____5 小时前
JAVA开源物联网平台
java·物联网·mqtt·开源·ruoyi
Lhuu(重开版5 小时前
JS:正则表达式和作用域
开发语言·javascript·正则表达式