栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

SpringBoot: RedisTemplate使用说明

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

SpringBoot: RedisTemplate使用说明

结论:如果自定义了一个名为redisTemplate的bean,则会替换掉自动装配的RedisTemplate Bean.如果名字不是redisTemplate,则会在容器中同时存在自定义的RedisTemplate实例和默认自动装配的RedisTemplate实例。所以在Autowired注解最好配合@Qualifier注解一起使用,以明确使用的是那个RedisTemplate的实例。
同时,Spring boot还会默认装配一个StringRedisTemplate类型的Bean.

RedisAutoConfiguration类的源码:


package org.springframework.boot.autoconfigure.data.redis;

import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnSingleCandidate;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Import;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.RedisOperations;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;


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

	@Bean
	@ConditionalOnMissingBean(name = "redisTemplate")
	@ConditionalOnSingleCandidate(RedisConnectionFactory.class)
	public RedisTemplate redisTemplate(RedisConnectionFactory redisConnectionFactory) {
		RedisTemplate template = new RedisTemplate<>();
		template.setConnectionFactory(redisConnectionFactory);
		return template;
	}

	@Bean
	@ConditionalOnMissingBean
	@ConditionalOnSingleCandidate(RedisConnectionFactory.class)
	public StringRedisTemplate stringRedisTemplate(RedisConnectionFactory redisConnectionFactory) {
		return new StringRedisTemplate(redisConnectionFactory);
	}

}

可以从第一个Bean中使用的注解@ConditionalOnMissingBean(name = “redisTemplate”)来证明上述结论。
Spring boot 官方文档里的一段:

If you add your own @Bean of any of the auto-configured types, it replaces the default (except in the
case of RedisTemplate, when the exclusion is based on the bean name, redisTemplate, not its type).

通常情况下,你配置某个类型的Bean,它就会替代系统默认装配的那个类型的Bean,
但是,对RedisTemplate是例外,你只有配置了名字为redisTemplate的Bean,它才会替代系统自动装配的类型为RedisTemplate的Bean

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/1020493.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号