如何解決redisTemplate注入為空問題
springboot2.*集成redis時(shí),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對(duì)象一直為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)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。
相關(guān)文章
java對(duì)象中什么時(shí)候適合用static修飾符踩坑解決記錄
這篇文章主要為大家介紹了java對(duì)象中什么時(shí)候適合用static修飾符踩坑解決記錄,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪2023-09-09Springboot 整合 Dubbo/ZooKeeper 實(shí)現(xiàn) SOA 案例解析
這篇文章主要介紹了Springboot 整合 Dubbo/ZooKeeper 詳解 SOA 案例,需要的朋友可以參考下2017-11-11使用IDEA將Java/Kotliin工程導(dǎo)出Jar包的正確姿勢(shì)
這篇文章主要介紹了使用IDEA將Java/Kotliin工程導(dǎo)出Jar包的正確姿勢(shì),文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2020-03-03springboot 使用Spring Boot Actuator監(jiān)控應(yīng)用小結(jié)
本篇文章主要介紹了springboot 使用Spring Boot Actuator監(jiān)控應(yīng)用小結(jié),小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,也給大家做個(gè)參考。一起跟隨小編過來看看吧2018-02-02