普通springboot项目 springboot版本3.0以上 在引入如下坐标后
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
在工具类中使用
@Autowired
RedisTemplate redisTemplate;
进行自动注入并使用,理论上来说到这里是没有问题的,因为 RedisAutoConfiguration 类中确定有定义这两个bean
但是在实际使用中总是无法注入,会报错说无法注入
Cannot invoke "org.springframework.data.redis.core.StringRedisTemplate.opsForValue()" because "this.stringRedisTemplate" is null
解决思路
- 使用@Resource注解试图注入,无效
- 新建一个测试项目,换个干净的环境,仍会出现上述错误,无效
- 配置文件问题,配置文件都有默认值,配置不配置都一样,无效
- 不使用自动装配,自己从头开始配置一个bean,有效
解决过程及代码 装好redis并确认可以使用后,在配置类中手动构建一个RedisTemplate
@Bean
public RedisTemplate redisTemplate(){
//spring3.0以后默认使用lettuce替代jedis
LettuceConnectionFactory lettuceConnectionFactory = new LettuceConnectionFactory();
//初始化 ,并在lettuceConnectionFactory中设置连接信息,不初始化会报错
lettuceConnectionFactory.afterPropertiesSet();
RedisTemplate redisTemplate = new RedisTemplate();
redisTemplate.setConnectionFactory(lettuceConnectionFactory);
redisTemplate.afterPropertiesSet();
//这两个应该是两个序列化器,不加会提示序列化错误
redisTemplate.setKeySerializer(new StringRedisSerializer());
redisTemplate.setValueSerializer(new StringRedisSerializer());
//此时RedisTemplata就能自动装配并使用了
return redisTemplate;
}
如果要使用jedis,请参照其他大神的文章,移除lettuce支持并更换为jedis
至于最终问题: 为什么无法自动装配,我没找到原因,只找到了解决办法