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;
    }
        
    // 可直接在其他静态方法中使用


}
相关推荐
Whisper_Sy4 小时前
Flutter for OpenHarmony移动数据使用监管助手App实战 - 网络状态实现
android·java·开发语言·javascript·网络·flutter·php
乂爻yiyao4 小时前
1.1 JVM 内存区域划分
java·jvm
Bony-5 小时前
Go语言垃圾回收机制详解与图解
开发语言·后端·golang
hmywillstronger5 小时前
【Rhino】【Python】 查询指定字段并cloud标注
开发语言·python
新缸中之脑5 小时前
Weave.js:开源实时白板库
开发语言·javascript·开源
我能坚持多久5 小时前
D16—C语言内功之数据在内存中的存储
c语言·开发语言
leo__5205 小时前
C#与三菱PLC串口通信源码实现(基于MC协议)
开发语言·c#
没有bug.的程序员5 小时前
Spring Cloud Eureka:注册中心高可用配置与故障转移实战
java·spring·spring cloud·eureka·注册中心
二十雨辰6 小时前
[python]-函数
开发语言·python
CryptoRzz6 小时前
如何高效接入日本股市实时数据?StockTV API 对接实战指南
java·python·kafka·区块链·状态模式·百度小程序