RedisTemplate自动注入为null的情况
在springboot项目中使用缓存redis时,如果依赖添加正确仍然出现自动注入为空的情况,可以尝试下面的操作。
写一个redis工具类
@Component
public class RedisUtil {
@Autowired
private RedisTemplate redisTemplate;
public static RedisTemplate redis;
@PostConstruct
public void getRedisTemplate(){
redis=this.redisTemplate;
}
}
然后在你的业务实现类如InvestorServiceImpl中调用改工具类实现赋值操作
@Override
public investor getDetail(String id) {
RedisTemplate redisTemplate= RedisUtil.redis;//通过工具类实现RedisTemplate 的创建
investor inv = null;
System.out.println(redisTemplate);
Object o = redisTemplate.opsForValue().get("investorId_" + id);
if(o!=null){
inv=(investor)o;
}else{//我这里是通过使用mybatis实现数据库的操作
SqlSession sqlSession= MybatisUtil.getSqlSession();
IInvestor iInvestor=sqlSession.getMapper(IInvestor.class);
inv=iInvestor.getDetail(id);
if(inv!=null){
redisTemplate.opsForValue().set("investorId_" + id,inv);
}
sqlSession.close();
}
return inv;
}
---
感谢观看