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;
    }
}
相关推荐
lv__pf13 小时前
redis【msb 2026金三银四redis上】
数据库·redis·缓存
spter。16 小时前
一次 Redis SETNX 的小插曲,我重新理解了原子性
前端·redis·bootstrap
星空19 小时前
Springboot复习
java·spring boot·spring
老郑聊AI业财智造20 小时前
TOGAF、DDD与微服务:软件架构的多维透视
spring boot·spring cloud·微服务·金融·架构·软件工程·制造
霸道流氓气质20 小时前
Redis Pub/Sub — 概念、原理、场景与代码示例
数据库·redis·缓存
wno70421 小时前
Spring Boot JdbcTemplate配置Druid多数据源
java·spring boot·后端
wear工程师21 小时前
Spring Boot 服务挂了却没重启?先分清 systemd 的三次判断
spring boot
夕除1 天前
redis--002
数据库·redis·缓存
旺仔学长 哈哈1 天前
52486|高校专业评估不再靠表格:Spring Boot 本科专业质量评估管理系统实战
数据库·spring boot·毕业设计·教育管理
weixin_BYSJ19871 天前
springboot小区物业管理小程序---附源码45555
java·javascript·spring boot·python·django·flask·php