問題描述
今天在寫一個工具類,里面用了@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)調用了