Bean and Annotations with Generics, how to do?

Asked

Viewed 152 times

4

I am in a project with Spring 4 configuring the Redis and a construction like this has emerged:

@Configuration
@ComponentScan({"com.empresa.sistema.web.util"})
public class RedisConfig {
    @Bean
    public RedisTemplate<String, Object> redisTemplate() {
        RedisTemplate<String, Object> template = new RedisTemplate<String, Object>();
        template.setConnectionFactory(jedisConnectionFactory());
        template.setKeySerializer(stringRedisSerializer());
        template.setHashKeySerializer(stringRedisSerializer());
        return template;
    }
}

It works perfectly, but now I wanted to do something like this:

@Bean
public RedisTemplate<String, T> redisTemplate() {
    RedisTemplate<String, T> template = new RedisTemplate<String, T>();
    template.setConnectionFactory(jedisConnectionFactory());
    template.setKeySerializer(stringRedisSerializer());
    template.setHashKeySerializer(stringRedisSerializer());
    return template;
}

How can I do?

1 answer

5


Answer: there is no way to do it without offering a type to the instance. What can be done is something like this:

@Bean
public RedisTemplate<String, MeuObjeto> redisTemplateMeuObjeto() {
    RedisTemplate<String, MeuObjeto> template = new RedisTemplate<String, MeuObjeto>();
    template.setConnectionFactory(jedisConnectionFactory());
    template.setKeySerializer(stringRedisSerializer());
    template.setHashKeySerializer(stringRedisSerializer());
    return template;
}

Before Spring 4, you have to use @Qualifier:

@Autowired
@Qualifier("redisTemplateMeuObjeto")
private RedisTemplate<String, MeuObjeto> customRedisTemplate;

Spring versions 4 onwards, one can only use the @Autowired, because with the class resource ResolvableType, the inference is automatic:

@Autowired
private RedisTemplate<String, MeuObjeto> customRedisTemplate;

Browser other questions tagged

You are not signed in. Login or sign up in order to post.