You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Spring Boot 3.2.2升级后Redis Bean冲突致依赖注入失败

解决Spring Boot 3.2.2中RedisTemplate Bean冲突问题

方法1:指定注入的Bean名称

在RedisOperation的构造方法参数上添加@Qualifier注解,明确指定要注入的自定义redisTemplate Bean:

import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.data.redis.core.RedisTemplate;

public class RedisOperation {
    private final RedisTemplate<String, Object> redisTemplate;

    public RedisOperation(@Qualifier("redisTemplate") RedisTemplate<String, Object> redisTemplate) {
        this.redisTemplate = redisTemplate;
    }
}

方法2:将自定义RedisTemplate设为Primary

在自定义RedisConfiguration的redisTemplate方法上添加@Primary注解,让Spring优先选择该Bean作为RedisTemplate类型的默认实现:

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.GenericJackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;

@Configuration
public class RedisConfiguration {

    @Primary
    @Bean
    public RedisTemplate<String, Object> redisTemplate(RedisConnectionFactory connectionFactory) {
        RedisTemplate<String, Object> template = new RedisTemplate<>();
        template.setConnectionFactory(connectionFactory);
        template.setKeySerializer(new StringRedisSerializer());
        template.setValueSerializer(new GenericJackson2JsonRedisSerializer());
        return template;
    }
}

方法3:排除StringRedisTemplate的自动配置

如果项目不需要StringRedisTemplate,可以在启动类上排除Redis自动配置类,完全使用自定义配置:

import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.autoconfigure.data.redis.RedisAutoConfiguration;

@SpringBootApplication(exclude = {RedisAutoConfiguration.class})
public class YourApplication {
    public static void main(String[] args) {
        SpringApplication.run(YourApplication.class, args);
    }
}

注意:排除自动配置后,需确保自定义配置覆盖了所有Redis相关Bean(如RedisConnectionFactory)的创建逻辑。

问题原因

Spring Boot的RedisAutoConfiguration会自动注册StringRedisTemplate Bean,而StringRedisTemplate是RedisTemplate<String, String>的子类。当你自定义了RedisTemplate<String, Object> Bean后,容器中存在两个可赋值给RedisTemplate类型的Bean(子类可向上转型),导致构造方法注入时出现歧义。

内容的提问来源于stack exchange,提问作者kernel

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.29 10:00:58