Spring @Autowired注解在非Controller中注入为null

问题描述

今天在写一个工具类,里面用了@Autowired注入了StringRedisTemplate以及RedisTemplate时,在template.opsForValue().set(key, obj)方法一直报 java.lang.nullpointerexception 异常,经过调试发现template为null。

Spring 注入失败

可能的原因: 网上百度了很久,原因可能在于我的utils包的类和controller的类不是同一个上下文。

解决办法

通过添加以下三个关键的地方,可以解决该问题

关于@PostConstruct:被@PostConstruct修饰的方法会在服务器加载Servlet的时候运行,并且只会被服务器调用一次,类似于Serclet的inti()方法。被@PostConstruct修饰的方法会在构造函数之后,init()方法之前运行。
//解决工具类中注入 3个步骤
@Component                     //关键步骤1,添加Component
public class RedisUtils {
    
    @Autowired
    private StringRedisTemplate stringRedisTemplate;
    @Autowired
    private RedisTemplate<String, Object> template;
    
    public static RedisUtils redisUtils;          // 关键2 添加该类的静态对象
    protected static Logger logger = LoggerFactory.getLogger(RedisUtils.class);
    
    public RedisUtils() {
    }
    
    // 关键3 用PostConstruct修饰init方法,并在init方法中对其赋值
    @PostConstruct
    public void init() {
        redisUtils = this;
        redisUtils.template = this.template;
        redisUtils.stringRedisTemplate = this.stringRedisTemplate;
    }
    

这样就可以通过redisUtils.template.opsForValue().set(key, obj)调用了

猜你喜欢

转载自www.cnblogs.com/zhangyongJava/p/9375483.html