使用@Autowired注入RedisTemplate时报java.lang.NullPointerException
生活随笔
收集整理的這篇文章主要介紹了
使用@Autowired注入RedisTemplate时报java.lang.NullPointerException
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
異常場景:
springboot項目中shiro與redis整合時,在ShiroConfig.java文件中customerRealm.setCacheManager(new RedisCacheManager());通過自定義new RedisCacheManager()開啟緩存管理。
問題描述:
自定義緩存管理器RedisCacheManager.java
//自定義redis緩存管理器 public class RedisCacheManager implements CacheManager {//參數:認證或者授權緩存的統一名稱@Overridepublic <K, V> Cache<K, V> getCache(String cacheName) throws CacheException {return new RedisCache<K,V>();} }自定義RedisCache.java,這里是解決方法,通過自定義工具類獲取redisTemplate,而不是通過自動注入方式。
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中傳入參數為beanName,一般通過spring注冊過的并且在不指定beanName情況下,默認為類名首字母小寫//假如為自定義的類,需要自己指定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);} }原因分析:
小白一個,還沒實戰開發,直接在RedisCache.java中使用注解@Resource或者@Autowired自動注入肯定不可以,畢竟該類并沒有通過注解@Componemt或其他注解來讓spring來管理。自己嘗試過加入@Componemt注解,但依舊不生效。猜測是因為該類是用于認證授權做緩存的,其工作原理可能并不能像普通自定義類一樣可以隨意交由工廠管理。而像其他地方,比如Controller中依舊是可以利用@Autowired來注入redisTemplate的
總結
以上是生活随笔為你收集整理的使用@Autowired注入RedisTemplate时报java.lang.NullPointerException的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: IDEA导入多层父子maven项目
- 下一篇: java.io.NotSerializa