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


}
相关推荐
一灯架构4 小时前
90%的人答错!一文带你彻底搞懂ArrayList
java·后端
踏着七彩祥云的小丑4 小时前
pytest——Mark标记
开发语言·python·pytest
Dream of maid4 小时前
Python12(网络编程)
开发语言·网络·php
W23035765735 小时前
经典算法:最长上升子序列(LIS)深度解析 C++ 实现
开发语言·c++·算法
Y4090015 小时前
【多线程】线程安全(1)
java·开发语言·jvm
不爱吃炸鸡柳5 小时前
Python入门第一课:零基础认识Python + 环境搭建 + 基础语法精讲
开发语言·python
布局呆星5 小时前
SpringBoot 基础入门
java·spring boot·spring
minji...6 小时前
Linux 线程同步与互斥(三) 生产者消费者模型,基于阻塞队列的生产者消费者模型的代码实现
linux·运维·服务器·开发语言·网络·c++·算法
Dxy12393102166 小时前
Python基于BERT的上下文纠错详解
开发语言·python·bert
风吹迎面入袖凉6 小时前
【Redis】Redisson的可重入锁原理
java·redis