background

The StringRedisTemplate template utility class provided by Spring-Data was recently used to integrate Redis with spring-boot.

The template class is directly used for dependency injection using @Resource in the Service implementation class.

Previous uses of StringRedisTemplate have included a config class that provides a StringRedisTemplate class in the form of an @bean to be managed by the Spring container:

@Configuration
public class RedisConfig {

    @Bean
    public StringRedisTemplate stringRedisTemplate(RedisConnectionFactory connectionFactory){
        return newStringRedisTemplate(connectionFactory); }}Copy the code

In one attempt, I didn’t write the config class, but the StringRedisTemplate template utility class was injected normally in the service without error.

This leads me to wonder: When was the StringRedisTemplate handed over to Spring to manage?

To solve

With that in mind, I started looking at the source file in spring-data-redis.jar, but couldn’t find any results.

Finally after query information and read in org. Springframework. Boot.. Jar source data.redis package to find the corresponding configuration file, source code as follows:

@Configuration
@ConditionalOnClass(RedisOperations.class)
@EnableConfigurationProperties(RedisProperties.class)
@Import({ LettuceConnectionConfiguration.class, JedisConnectionConfiguration.class })
public class RedisAutoConfiguration {

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

	@Bean
	@ConditionalOnMissingBean
	public StringRedisTemplate stringRedisTemplate( RedisConnectionFactory redisConnectionFactory) throws UnknownHostException {
		StringRedisTemplate template = new StringRedisTemplate();
		template.setConnectionFactory(redisConnectionFactory);
		returntemplate; }}Copy the code

Although I can’t fully read the source code at my level, I can infer from what I can that the configuration class already provides an instance object of StringRedisTemplate in the form of an @bean for Spring to manage, so I can directly use @Resource for injection.

conclusion

We know that one of the core aspects of Spring-Boot is automatic configuration: For many Spring applications and common application functions, Spring Boot provides automatic configuration.

Autoconfigure translates to automatic configuration.

So we can understand that Springboot provides automatic configuration for StringRedisTemplate, so we don’t have to manually provide configuration classes and hand over the StringRedisTemplate template class to Spring to manage. You just need to do dependency injection directly at use.

When was StringRedisTemplate handed over to the Spring container for management?