欢迎访问 生活随笔!

生活随笔

当前位置: 首页 >

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

发布时间:2025/1/21 59 豆豆
生活随笔 收集整理的这篇文章主要介绍了 使用@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的全部内容,希望文章能够帮你解决所遇到的问题。

如果觉得生活随笔网站内容还不错,欢迎将生活随笔推荐给好友。