After the spring upgrade, "Parameter 0 of the constructor in com.exampe.redis.operation.RedisOperation required a single bean, but 2 were found:" I'm getting the error.
spring-boot version: 3.2.2
<dependency>
<groupId>redis.clients</groupId>
<artifactId>jedis</artifactId>
<version>5.1.0</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
<exclusions>
<exclusion>
<groupId>io.lettuce</groupId>
<artifactId>lettuce-core</artifactId>
</exclusion>
</exclusions>
</dependency>
My RedisConfiguration.java
@AutoConfiguration
@ComponentScan(basePackages = {"com.example.redis"})
public class RedisConfiguration extends CachingConfigurerSupport {
@Bean
RedisTemplate redisTemplate(RedisConnectionFactory redisConnectionFactory) {
RedisTemplate redisTemplate = new RedisTemplate<>();
redisTemplate.setConnectionFactory(redisConnectionFactory);
redisTemplate.setKeySerializer(new StringRedisSerializer());
redisTemplate.setValueSerializer(new GenericJackson2JsonRedisSerializer());
redisTemplate.setHashKeySerializer(new StringRedisSerializer());
redisTemplate.setHashValueSerializer(new GenericJackson2JsonRedisSerializer());
return redisTemplate;
}
My RedisOperation.java class
@Component
public class RedisOperation {
private ValueOperations valueOperations;
public RedisOperation(RedisTemplate redisTemplate) {
this.valueOperations = redisTemplate.opsForValue();
}
...
}
resources/META-INF/spring/org.springframework.boot.autoconfigure.AutoConfiguration.imports file content
com.exampe.redis.config.RedisConfiguration
My Main Application class
@SpringBootApplication
@Import(ApplicationConfiguration.class)
@Configuration
@ComponentScan(basePackages = {"com.example"})
public class ExampleMain {
public static void main(String args[]) {
SpringApplication.run(ExampleMain.class, args);
}
}
application.properties
spring.cache.type=redis
spring.data.redis.host=localhost
spring.data.redis.port=9088
Error
Parameter 0 of constructor in com.example.redis.operation.RedisOperation required a single bean, but 2 were found:
- redisTemplate: defined by method 'redisTemplate' in class path resource [com/example/redis/config/RedisConfiguration.class]
- stringRedisTemplate: defined by method 'stringRedisTemplate' in class path resource [org/springframework/boot/autoconfigure/data/redis/RedisAutoConfiguration.class]
I fixed the problem by marking the redisTemplate bean @Primary.
@Bean
@Primary
RedisTemplate redisTemplate(RedisConnectionFactory redisConnectionFactory) {
RedisTemplate redisTemplate = new RedisTemplate<>();
redisTemplate.setConnectionFactory(redisConnectionFactory);
redisTemplate.setKeySerializer(new StringRedisSerializer());
redisTemplate.setValueSerializer(new GenericJackson2JsonRedisSerializer());
redisTemplate.setHashKeySerializer(new StringRedisSerializer());
redisTemplate.setHashValueSerializer(new GenericJackson2JsonRedisSerializer());
return redisTemplate;
}