redisTemplate注入為空


springboot2.*集成redis時,redis工具類中的redisTemplate注入后總是為空。

  • 問題代碼還原:

  1、工具類定義成靜態工具類,@Resource注入redisTemplate

 1 public class RedisCacheUtil {
 2     @Resource
 3     private static RedisTemplate<String, Object> redisTemplate;
 4 
 5     /**
 6      * 普通緩存獲取
 7      * @param key 鍵
 8      * @return 9      */
10     public static Object get(String key) {
11         return key == null ? null:redisTemplate.opsForValue().get(key); //redisTemplate對象一直為null 12     }
13 }    

  2、控制層直接調用工具類的靜態方法

    @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注入調用方

    @Resource
    private RedisCacheUtil redisCacheUtil;

    @RequestMapping("/getCache")
    public Object getCache(String key){
        return redisCacheUtil.get(key);
    }

至此,問題解決,僅做記錄。

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM