如何解決redisTemplate注入為空問題
更新時間:2020年07月24日 11:04:00 作者:這,看不懂
這篇文章主要介紹了如何解決redisTemplate注入為空問題,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友可以參考下
springboot2.*集成redis時,redis工具類中的redisTemplate注入后總是為空。
問題代碼還原:
1、工具類定義成靜態(tài)工具類,@Resource注入redisTemplate
public class RedisCacheUtil { @Resource private static RedisTemplate<String, Object> redisTemplate; /** * 普通緩存獲取 * @param key 鍵 * @return 值 */ public static Object get(String key) { return key == null ? null:redisTemplate.opsForValue().get(key); //redisTemplate對象一直為null } }
2、控制層直接調(diào)用工具類的靜態(tài)方法
@RequestMapping("/getCache") public Object getCache(String key){ return RedisCacheUtil.get(key); }
解決方案:
1、將工具類注入到spring容器
@Component //注入spring容器 public class RedisCacheUtil { @Resource private RedisTemplate<String, Object> redisTemplate; /** * 普通緩存獲取 * @param key 鍵 * @return 值 */ public Object get(String key) { return key == null ? null : redisTemplate.opsForValue().get(key); } }
2、再將工具類bean注入調(diào)用方
@Resource private RedisCacheUtil redisCacheUtil; @RequestMapping("/getCache") public Object getCache(String key){ return redisCacheUtil.get(key); }
至此,問題解決,僅做記錄。
以上就是本文的全部內(nèi)容,希望對大家的學習有所幫助,也希望大家多多支持腳本之家。
相關文章
Springboot 整合 Dubbo/ZooKeeper 實現(xiàn) SOA 案例解析
這篇文章主要介紹了Springboot 整合 Dubbo/ZooKeeper 詳解 SOA 案例,需要的朋友可以參考下2017-11-11使用IDEA將Java/Kotliin工程導出Jar包的正確姿勢
這篇文章主要介紹了使用IDEA將Java/Kotliin工程導出Jar包的正確姿勢,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習學習吧2020-03-03springboot 使用Spring Boot Actuator監(jiān)控應用小結(jié)
本篇文章主要介紹了springboot 使用Spring Boot Actuator監(jiān)控應用小結(jié),小編覺得挺不錯的,現(xiàn)在分享給大家,也給大家做個參考。一起跟隨小編過來看看吧2018-02-02