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;
    }
}
相关推荐
源码_空间42 分钟前
基于Springboot的在线错题本与复习计划系统(源码+文档)
java·spring boot·后端
himobrinehacken1 小时前
HackMyVM靶机Yulian
java·spring boot·后端
Monkey的自我迭代1 小时前
微服务架构实践:K8s、RocketMQ、Nacos、Redis、MinIO、Nexus 组件落地经验
redis·nacos·k8s·rocketmq
霸道流氓气质2 小时前
分布式序列号生成:基于 Redis 原子自增的编号方案
数据库·redis·分布式
源码_空间3 小时前
基于SpringBoot的在线技能闯关与数字徽章平台(源码+文档)
java·spring boot·后端
用户80587957201624 小时前
1000人抢100头牛:Spring Boot悲观锁与事务防超卖实战
spring boot
长不大的杨瑞杰5 小时前
Spring Boot 4 + Java 25 虚拟线程实战:配置、压测、限流与线上排障
java·spring boot·后端·spring·软件工程
圆心角6 小时前
前端转 Java 全栈:依赖、入口、路由、中间件到底放哪
java·spring boot·后端
幽默小吴6 小时前
Redis篇(十六)
数据库·redis·bootstrap
IT研究室6 小时前
最新计算机毕业设计选题推荐-基于spring boot的高校竞赛管理系统-网站-文档指导-Java-springboot
java·spring boot·课程设计