如何解決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)容,希望對大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。
相關(guān)文章
淺談spring中的default-lazy-init參數(shù)和lazy-init
下面小編就為大家?guī)硪黄獪\談spring中的default-lazy-init參數(shù)和lazy-init。小編覺得挺不錯的,現(xiàn)在就分享給大家,也給大家做個參考。一起跟隨小編過來看看吧2017-04-04
WebSocket獲取httpSession空指針異常的解決辦法
這篇文章主要介紹了在使用WebSocket實現(xiàn)p2p或一對多聊天功能時,如何獲取HttpSession來獲取用戶信息,本文結(jié)合實例代碼給大家介紹的非常詳細,感興趣的朋友一起看看吧2025-01-01
MyBatis攔截器如何自動設(shè)置創(chuàng)建時間和修改時間
文章介紹了如何通過實現(xiàn)MyBatis的Interceptor接口,在實體類中自動設(shè)置創(chuàng)建時間和修改時間,從而提高開發(fā)效率2025-02-02
spring security動態(tài)配置url權(quán)限的2種實現(xiàn)方法
對于使用spring security來說,存在一種需求,就是動態(tài)去配置url的權(quán)限,即在運行時去配置url對應(yīng)的訪問角色。下面這篇文章主要給大家介紹了關(guān)于spring security動態(tài)配置url權(quán)限的2種實現(xiàn)方法,需要的朋友可以參考下2018-06-06

