背景
容器里配置兩個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沒有命名,都仔仔細(xì)細(xì)檢查過了,重啟N遍,依然出現(xià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源碼發(fā)現(xiàn)一段:
/**
* 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,所以才報了上面的錯誤
結(jié)論
將配置的其中一個redisTemplate Bean的名稱改為redisTemplate,這樣RedisAutoConfiguration就不會再加載默認(rèn)的了