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;
    }
}
相关推荐
ShiXZ2131 小时前
Redis 常用指令全集:redis-cli 实战速查手册
数据库·redis·缓存
Muscleheng4 小时前
SpringBoot 集成 DeepSeek 实现 RAG 文档问答
java·spring boot·ai·springai
suconnect8 小时前
Spring Boot接入企业RAG:文档切分、向量检索、权限过滤和答案溯源
java·spring boot·后端
weixin_BYSJ19878 小时前
springboot校园自习室管理小程序---附源码32142
java·javascript·spring boot·python·django·flask·php
旺仔学长 哈哈8 小时前
Spring Boot 智能停车场管理系统---附源码+数据库文档
数据库·spring boot·后端·智能停车场
小Ti客栈8 小时前
SpringBoot 事件发布机制:原理与应用
java·spring boot·spring
huahailing102411 小时前
Spring Boot 集成 XXL-Job 完整实现方案(支持动态CRUD)
java·spring boot·后端
音符犹如代码13 小时前
Arthas Profiler 火焰图实战:CPU 热点在哪一目了然
java·jvm·spring boot
阿里云云原生13 小时前
AI Agent 上线容易稳定难?阿里云 AgentLoop 推出“经验自进化”闭环治理方案
人工智能·阿里云·mybatis·agentscope
大模型丫丫14 小时前
Spring Boot 入门指南:从零开始构建微服务
spring boot·微服务·firefox