日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當(dāng)前位置: 首頁 > 运维知识 > 数据库 >内容正文

数据库

使用@Autowired注入RedisTemplate时报java.lang.NullPointerException

發(fā)布時(shí)間:2025/1/21 数据库 41 豆豆
生活随笔 收集整理的這篇文章主要介紹了 使用@Autowired注入RedisTemplate时报java.lang.NullPointerException 小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.

異常場景:

springboot項(xiàng)目中shiro與redis整合時(shí),在ShiroConfig.java文件中customerRealm.setCacheManager(new RedisCacheManager());通過自定義new RedisCacheManager()開啟緩存管理。


問題描述:

自定義緩存管理器RedisCacheManager.java

//自定義redis緩存管理器 public class RedisCacheManager implements CacheManager {//參數(shù):認(rèn)證或者授權(quán)緩存的統(tǒng)一名稱@Overridepublic <K, V> Cache<K, V> getCache(String cacheName) throws CacheException {return new RedisCache<K,V>();} }

自定義RedisCache.java,這里是解決方法,通過自定義工具類獲取redisTemplate,而不是通過自動(dòng)注入方式。

public class RedisCache<K,V> implements Cache<K,V> {public RedisCache() {}@Overridepublic V get(K k) throws CacheException {return (V)getRedisTemplate().opsForValue().get(k.toString());}@Overridepublic V put(K k, V v) throws CacheException {getRedisTemplate().opsForValue().set(k.toString(),v);return null;} //省略其他無用方法......private RedisTemplate getRedisTemplate(){RedisTemplate redisTemplate = (RedisTemplate) //getBean中傳入?yún)?shù)為beanName,一般通過spring注冊過的并且在不指定beanName情況下,默認(rèn)為類名首字母小寫//假如為自定義的類,需要自己指定beanNameApplicationContextUtils.getBean("redisTemplate"); redisTemplate.setKeySerializer(new StringRedisSerializer());return redisTemplate;}} import org.springframework.beans.BeansException; import org.springframework.context.ApplicationContext; import org.springframework.context.ApplicationContextAware; import org.springframework.stereotype.Component;@Component public class ApplicationContextUtils implements ApplicationContextAware {private static ApplicationContext context;@Overridepublic void setApplicationContext(ApplicationContext applicationContext) throws BeansException {context = applicationContext;}public static Object getBean(String beanName){return context.getBean(beanName);} }

原因分析:

小白一個(gè),還沒實(shí)戰(zhàn)開發(fā),直接在RedisCache.java中使用注解@Resource或者@Autowired自動(dòng)注入肯定不可以,畢竟該類并沒有通過注解@Componemt或其他注解來讓spring來管理。自己嘗試過加入@Componemt注解,但依舊不生效。猜測是因?yàn)樵擃愂怯糜谡J(rèn)證授權(quán)做緩存的,其工作原理可能并不能像普通自定義類一樣可以隨意交由工廠管理。而像其他地方,比如Controller中依舊是可以利用@Autowired來注入redisTemplate的


總結(jié)

以上是生活随笔為你收集整理的使用@Autowired注入RedisTemplate时报java.lang.NullPointerException的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網(wǎng)站內(nèi)容還不錯(cuò),歡迎將生活随笔推薦給好友。