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;
    }
}
相关推荐
阿丰资源18 小时前
基于SpringBoot的物流信息管理系统设计与实现(附资料)
java·spring boot·后端
lhbian1 天前
PHP、C++和C语言对比:哪个更适合你?
android·数据库·spring boot·mysql·kafka
zhimingwen1 天前
初探 Java 後端開發:解決 macOS 環境下 Spring Boot 項目啟動的各類「坑」
java·spring boot
Arya_aa1 天前
检疫登记模块图片上传,nginx自动映射地址
spring boot·nginx
程序员老邢1 天前
【技术底稿 15】SpringBoot 异步文件上传实战:多线程池隔离 + 失败重试 + 实时状态推送
java·经验分享·spring boot·后端·程序人生·spring
Arya_aa1 天前
HTTP与Tmocat服务器与SpringMVC
java·spring boot
songcream11 天前
Spring Boot资料整理
java·spring boot·后端
披着羊皮不是狼1 天前
(8):实现双删(MySQL+Redis)
spring boot·后端
lhbian1 天前
PHP vs Java vs Go:编程语言终极对比
java·spring boot·后端·kafka·linq
java修仙传1 天前
从手写 Redis 锁到 Redisson:我对分布式锁安全性的理解
java·数据库·redis·分布式