spring 中配置两个redis导致的NoUniqueBeanDefinitionException异常

背景

容器里配置两个RedisConnectFactory实例,报错如下

Description:

Parameter 0 of method redisTemplate in org.springframework.boot.autoconfigure.data.redis.RedisAutoConfiguration$RedisConfiguration required a single bean, but 2 were found:
    - desCacheJedisConnectionFactory: defined by method 'desCachejedisConnectionFactory' in class path resource [com/qingqing/des/config/RedisConfig.class]
    - apiDesJedisConnectionFactory: defined by method 'apiDesJedisConnectionFactory' in class path resource [com/qingqing/des/config/RedisConfig.class]


Action:

Consider marking one of the beans as @Primary, updating the consumer to accept multiple beans, or using @Qualifier to identify the bean that should be consumed

分析

开始以为是配置的bean没有命名,都仔仔细细检查过了,重启N遍,依然出现这个问题,然后我就在异常里面看到 redisTemplate这个Bean,搜了项目里的配置,我并没有这个,所以怀疑是RedisAutoConfiguration里面自动加载了一个redisTemplate.

Caused by: org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'redisTemplate' defined in class path resource [org/springframework/boot/autoconfigure/data/redis/RedisAutoConfiguration$RedisConfiguration.class]: Unsatisfied dependency expressed through method 'redisTemplate' parameter 0; nested exception is org.springframework.beans.factory.NoUniqueBeanDefinitionException: No qualifying bean of type 'org.springframework.data.redis.connection.RedisConnectionFactory' available: expected single matching bean but found 2: desCacheJedisConnectionFactory,apiDesJedisConnectionFactory
 

看RedisAutoConfiguration源码发现一段:

    /**
     * Standard Redis configuration.
     */
    @Configuration
    protected static class RedisConfiguration {

        @Bean
        @ConditionalOnMissingBean(name = "redisTemplate")
        public RedisTemplate<Object, Object> redisTemplate(
                RedisConnectionFactory redisConnectionFactory)
                        throws UnknownHostException {
            RedisTemplate<Object, Object> template = new RedisTemplate<Object, Object>();
            template.setConnectionFactory(redisConnectionFactory);
            return template;
        }

        @Bean
        @ConditionalOnMissingBean(StringRedisTemplate.class)
        public StringRedisTemplate stringRedisTemplate(
                RedisConnectionFactory redisConnectionFactory)
                        throws UnknownHostException {
            StringRedisTemplate template = new StringRedisTemplate();
            template.setConnectionFactory(redisConnectionFactory);
            return template;
        }

    }

ConditionalOnMissingBean这个注释表示如果容器没有这个类则加载,我的程序没有定义redisTemplate的Bean,所以这个地方自动加载了,但是容器里又有两个redisConnectionFactory,所以才报了上面的错误

结论

将配置的其中一个redisTemplate Bean的名称改为redisTemplate,这样RedisAutoConfiguration就不会再加载默认的了

©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容