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

异常场景:

springboot项目中shiro与redis整合时,在ShiroConfig.java文件中customerRealm.setCacheManager(new RedisCacheManager());通过自定义new RedisCacheManager()开启缓存管理。


问题描述:

自定义缓存管理器RedisCacheManager.java

//自定义redis缓存管理器
public class RedisCacheManager implements CacheManager {
    //参数:认证或者授权缓存的统一名称
    @Override
    public <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() {
    }

    @Override
    public V get(K k) throws CacheException {
        return (V)getRedisTemplate().opsForValue().get(k.toString());
    }

    @Override
    public 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情况下,默认为类名首字母小写
        //假如为自定义的类,需要自己指定beanName
        ApplicationContextUtils.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;
    @Override
    public 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的


  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值