Redis报错:A bean with that name has already been defined in class path resource

1. 报错信息

Description:

The bean 'redisTemplate', defined in class path resource [xxx/xxx/xxx], could not be registered. A bean with that name has already been defined in class path resource [org/springframework/boot/autoconfigure/data/redis/RedisAutoConfiguration.class] and overriding is disabled.

Action:

Consider renaming one of the beans or enabling overriding by setting spring.main.allow-bean-definition-overriding=true

2. 错误信息解析

由错误信息可以看出,redis报错,这个错误说:无法创建一个名字为redisTemplate的bean,原因是这个名字的bean已经存在了,再创建就会报错

3. 解决方案

怎么解决呢?其实spring框架已经告诉我们怎么解决,如高亮所示,让我们考虑加上注解:

复制代码
@ConditionalOnMissingBean(name = "redisTemplate")

注意:name的值需要看你的redis的配置config文件里面定义的redis的bean的名字,不一定和博主的name相同

这个注解的意思是:只有当没有同名的bean才会创建

java 复制代码
@Configuration
public class RedisConfig {
    
    @Bean
    @ConditionalOnMissingBean(name = "redisTemplate") // 只有当没有同名的 bean 时才创建
    public RedisTemplate<String, Object> redisTemplate(RedisConnectionFactory redisConnectionFactory) {
        RedisTemplate<String, Object> template = new RedisTemplate<>();
        template.setConnectionFactory(redisConnectionFactory);

        // 设置 key 的序列化器
        template.setKeySerializer(new StringRedisSerializer());
        template.setHashKeySerializer(new StringRedisSerializer());

        // 设置 value 的序列化器
        template.setValueSerializer(new GenericJackson2JsonRedisSerializer());
        template.setHashValueSerializer(new GenericJackson2JsonRedisSerializer());

        template.afterPropertiesSet();
        return template;
    }
}
相关推荐
Coder_Boy_6 分钟前
基于Spring AI的分布式在线考试系统-事件处理架构实现方案
人工智能·spring boot·分布式·spring
啦啦啦_999916 分钟前
Redis-5-doFormatAsync()方法
数据库·redis·c#
生产队队长25 分钟前
Redis:Windows环境安装Redis,并将 Redis 进程注册为服务
数据库·redis·缓存
老毛肚1 小时前
手写mybatis
java·数据库·mybatis
xu_yule1 小时前
Redis存储(15)Redis的应用_分布式锁_Lua脚本/Redlock算法
数据库·redis·分布式
毕设源码-钟学长2 小时前
【开题答辩全过程】以 基于Springboot的扶贫众筹平台为例,包含答辩的问题和答案
java·spring boot·后端
Java水解3 小时前
Spring Boot 4 升级指南:告别RestTemplate,拥抱现代HTTP客户端
spring boot·后端
神云瑟瑟3 小时前
spring boot拦截器获取requestBody的最佳实践
spring boot·拦截器·requestbody
暮色妖娆丶3 小时前
Spring 源码分析 BeanFactoryPostProcessor
spring boot·spring·源码
南极企鹅4 小时前
springBoot项目有几个端口
java·spring boot·后端