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;
    }
}
相关推荐
leoZ23133 分钟前
2026-09-09-springboot-cloud-deploy-pitfalls
java·前端·javascript·vue.js·人工智能·spring boot·后端
hweiyu003 小时前
Redis命令:UNLINK
redis·缓存
Shaoxi Zhang3 小时前
Redis基础——五种核心数据结构(“容器”)
redis
孫治AllenSun3 小时前
【LangChain4J-09】开发学习知识点
spring boot·后端·学习
林石工作室4 小时前
体育直播APP从0到1搭建指南:技术选型、核心模块与部署实战
spring boot·流媒体·app搭建·体育直播app·星逐赛事
LXMXHJ6 小时前
springboot中的线程操作
java·spring boot·后端·线程
行百里er7 小时前
BlockingQueue:异步批量上报
spring boot·spring cloud·监控
武哥聊编程9 小时前
【AI实战项目】AI Agent数据分析平台,基于SpringAI+Springboot+Vue+Agent的电商数据分析平台
人工智能·spring boot·数据分析·springai
计算机毕设定制辅导-无忧学长10 小时前
《基于SpringBoot的庭院玫瑰栽培养护知识交互式科普平台设计与实现》
java·spring boot·后端·毕业设计·个性化推荐·协同过滤算法·庭院玫瑰栽培养护知识科普平台
骇客野人10 小时前
SpringBoot数十Jar包批量生产部署落地实施方案(Shell+Systemd完整版)
spring boot·后端·jar