Confusion about the spring beans with the same type and different parameter as the parameter of another function

4174 views spring-boot
-3

To customize LettuceConnectionFactory, I have created the two functions, which have same return type and different parameters, one is single node config, other is cluster config. The code as follows:

@Component
@Configuration
public class RedisConfig {

    @Bean(name = "singleFactory")
    public LettuceConnectionFactory createSingleFactory(RedisSingleConfig redisSingleConfig){...}

    @Bean(name = "clusterFactory")
    public LettuceConnectionFactory createClusterFactory(RedisClusterConfig redisClusterConfig){...}

}

when they are called, the return value(LettuceConnectionFactory) is a parameter of another function. The code as follows:

@Autowired
private RedisActivityClusterConfig testConfig;

@Autowired
private RedisItemConfig redisItemConfig;

@Autowired
private RedisConfig redisConfig;

@Autowired
private StringRedisTemplate redisTemplate;

@Test
public void test(){
    redisTemplate.setConnectionFactory(redisConfig.createClusterFactory(testConfig));
    ValueOperations<String, String> valueOperations = redisTemplate.opsForValue();
    System.out.println(valueOperations.get("test"));
}

But in the way, spring will report No qualifying bean of type 'org.springframework.data.redis.connection.RedisConnectionFactory' available: expected single matching bean but found 2: singleFactory,clusterFactory

springboot: 2.1.0.release

jdk8

Sincerely ask for some solutions. Thanks

answered question

1 Answer

7

Since you are manually creating & setting the LettuceConnectionFactory into redisTemplate you don't need to mark them as beans, even with different names, they are conflicting the native autowiring that is being done I guess, since they are of type RedisConnectionFactory. Just making these methods pure LettuceConnectionFactory constructors would suffice.

public class RedisFactoryFactory {

    public static LettuceConnectionFactory createSingleFactory(RedisSingleConfig redisSingleConfig){...}

    public static LettuceConnectionFactory createClusterFactory(RedisClusterConfig redisClusterConfig){...}
}

posted this

Have an answer?

JD

Please login first before posting an answer.