spring boot 自动配置篇1

1.redis 自动配置

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>

application内的相关配置

#redis服务host地址
spring.redis.host=localhost
#redis服务端口
spring.redis.port=6379
#redis连接密码 auth协议
spring.redis.password=
#在集群情况下,一条redis命令执行时最多转发次数
spring.redis.cluster.max-redirects=5
#集群中每个节点的url,以host:port的形式给出
spring.redis.cluster.nodes[0]=127.0.0.1:6378
spring.redis.cluster.nodes[1]=127.0.0.1:6379
#链接redis时默认链接的数据库编号
spring.redis.database=0
#同一时间,连接池能给出的最大连接数,设置负数标识没有限制
spring.redis.pool.max-active=8
#当连接池没有可用资源时,最大等待时间(毫秒),负数标识没有限制
spring.redis.pool.max-wait=-1
#连接池最大空闲连接数,负数标识没有限制
spring.redis.pool.max-idle=8
#连接池最小空闲连接数,负数标识没有限制
spring.redis.pool.min-idle=0
#redis检查服务master节点的名称
spring.redis.sentinel.master=
#redis检查服务节点url,以host:port的形式给出
spring.redis.sentinel.nodes=
#链接redis时是否启用ssl加密协议
spring.redis.ssl=false
#与redis建立连接时的超时限制,0标识没有超时限制
spring.redis.timeout=0
#url host:port
spring.redis.url=127.0.0.1:6379

使用方式

@Autowired
private StringRedisTemplate template;

public void hset(String key, String field, String value) {
    template.opsForHash().put(key, field, value);
}

这里的StringRedisTemplateRedisTemplate<String, String>的一个具体实现

RedisTemplate<K, V> 是一个泛型类

​ K:redis key的类型

​ V:redis value的类型

一般来说,K,V均为String

通常我们不直接使用RedisTemplate<String, String> 而是使用一个继承自它的类,比如StringRedisTemplate 或者我们也可以自己写一个工具类来继承它,期间我们需要实现一个RedisSerializer<String> 这个类是一个序列化器,在程序与redis进行交互时,对数据进行序列化操作,官方有一个默认实现,代码也比较简单易读

public class StringRedisSerializer implements RedisSerializer<String> {

   private final Charset charset;

   public StringRedisSerializer() {
      this(Charset.forName("UTF8"));
   }

   public StringRedisSerializer(Charset charset) {
      Assert.notNull(charset, "Charset must not be null!");
      this.charset = charset;
   }

   public String deserialize(byte[] bytes) {
      return (bytes == null ? null : new String(bytes, charset));
   }

   public byte[] serialize(String string) {
      return (string == null ? null : string.getBytes(charset));
   }
}

继续说自定义RedisTemplate,我们只需要实现或者使用这个已经被实现的RedisSerializer<String> 并设置到父类RedisTemplate<String, String> 即可使用

/**
 * author: qianweifeng
 * date: 2017/7/18
 * function:
 */
public class RedisTemplateUtil extends RedisTemplate<String, String> {
    public RedisTemplateUtil() {
        StringRedisSerializer stringSerializer = new StringRedisSerializer();
        this.setKeySerializer(stringSerializer);
        this.setValueSerializer(stringSerializer);
        this.setHashKeySerializer(stringSerializer);
        this.setHashValueSerializer(stringSerializer);
    }

    public RedisTemplateUtil(RedisConnectionFactory connectionFactory) {
        this();
        this.setConnectionFactory(connectionFactory);
        this.afterPropertiesSet();
    }

    protected RedisConnection preProcessConnection(RedisConnection connection, boolean existingConnection) {
        return new DefaultStringRedisConnection(connection);
    }
}

进行配置与注入

@Configuration
public class RedisCustomerConfig {

    @Bean
    @ConditionalOnMissingBean(RedisTemplateUtil.class)
    public RedisTemplateUtil redisTemplateUtil(
            RedisConnectionFactory redisConnectionFactory)
            throws UnknownHostException {
        RedisTemplateUtil template = new RedisTemplateUtil();
        template.setConnectionFactory(redisConnectionFactory);
        return template;
    }
}

接下来就可以使用我们自定义的RedisTemplateUtil来操作Redis了

Spring Boot是如何自动装配Redis相关配置的

自动配置依赖于:spring-boot-autoconfigure包

在其目录META-INF下的spring.factories内记录了需要进行自动装配的类,我截取部分展示

# Initializers
org.springframework.context.ApplicationContextInitializer=\
org.springframework.boot.autoconfigure.SharedMetadataReaderFactoryContextInitializer,\
org.springframework.boot.autoconfigure.logging.AutoConfigurationReportLoggingInitializer

# Application Listeners
org.springframework.context.ApplicationListener=\
org.springframework.boot.autoconfigure.BackgroundPreinitializer

# Auto Configuration Import Listeners
org.springframework.boot.autoconfigure.AutoConfigurationImportListener=\
org.springframework.boot.autoconfigure.condition.ConditionEvaluationReportAutoConfigurationImportListener

# Auto Configuration Import Filters
org.springframework.boot.autoconfigure.AutoConfigurationImportFilter=\
org.springframework.boot.autoconfigure.condition.OnClassCondition

# Auto Configure
org.springframework.boot.autoconfigure.EnableAutoConfiguration=\
org.springframework.boot.autoconfigure.admin.SpringApplicationAdminJmxAutoConfiguration,\
org.springframework.boot.autoconfigure.aop.AopAutoConfiguration,\
org.springframework.boot.autoconfigure.amqp.RabbitAutoConfiguration,\
org.springframework.boot.autoconfigure.batch.BatchAutoConfiguration,\
org.springframework.boot.autoconfigure.cache.CacheAutoConfiguration,\
org.springframework.boot.autoconfigure.cassandra.CassandraAutoConfiguration,\
org.springframework.boot.autoconfigure.cloud.CloudAutoConfiguration,\
org.springframework.boot.autoconfigure.context.ConfigurationPropertiesAutoConfiguration,\
org.springframework.boot.autoconfigure.context.MessageSourceAutoConfiguration,\
org.springframework.boot.autoconfigure.context.PropertyPlaceholderAutoConfiguration,\
org.springframework.boot.autoconfigure.couchbase.CouchbaseAutoConfiguration,\
org.springframework.boot.autoconfigure.dao.PersistenceExceptionTranslationAutoConfiguration,\
org.springframework.boot.autoconfigure.data.cassandra.CassandraDataAutoConfiguration,\
org.springframework.boot.autoconfigure.data.cassandra.CassandraRepositoriesAutoConfiguration,\
org.springframework.boot.autoconfigure.data.couchbase.CouchbaseDataAutoConfiguration,\
org.springframework.boot.autoconfigure.data.couchbase.CouchbaseRepositoriesAutoConfiguration,\
org.springframework.boot.autoconfigure.data.elasticsearch.ElasticsearchAutoConfiguration,\
org.springframework.boot.autoconfigure.data.elasticsearch.ElasticsearchDataAutoConfiguration,\
org.springframework.boot.autoconfigure.data.elasticsearch.ElasticsearchRepositoriesAutoConfiguration,\
org.springframework.boot.autoconfigure.data.jpa.JpaRepositoriesAutoConfiguration,\
org.springframework.boot.autoconfigure.data.ldap.LdapDataAutoConfiguration,\
org.springframework.boot.autoconfigure.data.ldap.LdapRepositoriesAutoConfiguration,\
org.springframework.boot.autoconfigure.data.mongo.MongoDataAutoConfiguration,\
org.springframework.boot.autoconfigure.data.mongo.MongoRepositoriesAutoConfiguration,\
org.springframework.boot.autoconfigure.data.neo4j.Neo4jDataAutoConfiguration,\
org.springframework.boot.autoconfigure.data.neo4j.Neo4jRepositoriesAutoConfiguration,\
org.springframework.boot.autoconfigure.data.solr.SolrRepositoriesAutoConfiguration,\
org.springframework.boot.autoconfigure.data.redis.RedisAutoConfiguration,\
org.springframework.boot.autoconfigure.data.redis.RedisRepositoriesAutoConfiguration,\
org.springframework.boot.autoconfigure.data.rest.RepositoryRestMvcAutoConfiguration,\
org.springframework.boot.autoconfigure.data.web.SpringDataWebAutoConfiguration,\
org.springframework.boot.autoconfigure.elasticsearch.jest.JestAutoConfiguration,\
org.springframework.boot.autoconfigure.freemarker.FreeMarkerAutoConfiguration,\
org.springframework.boot.autoconfigure.gson.GsonAutoConfiguration,\
org.springframework.boot.autoconfigure.h2.H2ConsoleAutoConfiguration,\
org.springframework.boot.autoconfigure.hateoas.HypermediaAutoConfiguration,\
org.springframework.boot.autoconfigure.hazelcast.HazelcastAutoConfiguration,\
org.springframework.boot.autoconfigure.hazelcast.HazelcastJpaDependencyAutoConfiguration,\
org.springframework.boot.autoconfigure.info.ProjectInfoAutoConfiguration,\
org.springframework.boot.autoconfigure.integration.IntegrationAutoConfiguration,\
org.springframework.boot.autoconfigure.jackson.JacksonAutoConfiguration,\
org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration,\
org.springframework.boot.autoconfigure.jdbc.JdbcTemplateAutoConfiguration,\
org.springframework.boot.autoconfigure.jdbc.JndiDataSourceAutoConfiguration,\
org.springframework.boot.autoconfigure.jdbc.XADataSourceAutoConfiguration,\
org.springframework.boot.autoconfigure.jdbc.DataSourceTransactionManagerAutoConfiguration,\
org.springframework.boot.autoconfigure.jms.JmsAutoConfiguration,\
org.springframework.boot.autoconfigure.jmx.JmxAutoConfiguration,\
org.springframework.boot.autoconfigure.jms.JndiConnectionFactoryAutoConfiguration,\
org.springframework.boot.autoconfigure.jms.activemq.ActiveMQAutoConfiguration,\
org.springframework.boot.autoconfigure.jms.artemis.ArtemisAutoConfiguration,\
org.springframework.boot.autoconfigure.flyway.FlywayAutoConfiguration,\
org.springframework.boot.autoconfigure.groovy.template.GroovyTemplateAutoConfiguration,\
org.springframework.boot.autoconfigure.jersey.JerseyAutoConfiguration,\
org.springframework.boot.autoconfigure.jooq.JooqAutoConfiguration,\
org.springframework.boot.autoconfigure.kafka.KafkaAutoConfiguration,\
org.springframework.boot.autoconfigure.ldap.embedded.EmbeddedLdapAutoConfiguration,\
org.springframework.boot.autoconfigure.ldap.LdapAutoConfiguration,\
org.springframework.boot.autoconfigure.liquibase.LiquibaseAutoConfiguration,\
org.springframework.boot.autoconfigure.mail.MailSenderAutoConfiguration,\
org.springframework.boot.autoconfigure.mail.MailSenderValidatorAutoConfiguration,\
org.springframework.boot.autoconfigure.mobile.DeviceResolverAutoConfiguration,\
org.springframework.boot.autoconfigure.mobile.DeviceDelegatingViewResolverAutoConfiguration,\
org.springframework.boot.autoconfigure.mobile.SitePreferenceAutoConfiguration,\
org.springframework.boot.autoconfigure.mongo.embedded.EmbeddedMongoAutoConfiguration,\
org.springframework.boot.autoconfigure.mongo.MongoAutoConfiguration,\
org.springframework.boot.autoconfigure.mustache.MustacheAutoConfiguration,\
org.springframework.boot.autoconfigure.orm.jpa.HibernateJpaAutoConfiguration,\
org.springframework.boot.autoconfigure.reactor.ReactorAutoConfiguration,\
org.springframework.boot.autoconfigure.security.SecurityAutoConfiguration,\
org.springframework.boot.autoconfigure.security.SecurityFilterAutoConfiguration,\
org.springframework.boot.autoconfigure.security.FallbackWebSecurityAutoConfiguration,\
org.springframework.boot.autoconfigure.security.oauth2.OAuth2AutoConfiguration,\
org.springframework.boot.autoconfigure.sendgrid.SendGridAutoConfiguration,\
org.springframework.boot.autoconfigure.session.SessionAutoConfiguration,\
org.springframework.boot.autoconfigure.social.SocialWebAutoConfiguration,\
org.springframework.boot.autoconfigure.social.FacebookAutoConfiguration,\
org.springframework.boot.autoconfigure.social.LinkedInAutoConfiguration,\
org.springframework.boot.autoconfigure.social.TwitterAutoConfiguration,\
org.springframework.boot.autoconfigure.solr.SolrAutoConfiguration,\
org.springframework.boot.autoconfigure.thymeleaf.ThymeleafAutoConfiguration,\
org.springframework.boot.autoconfigure.transaction.TransactionAutoConfiguration,\
org.springframework.boot.autoconfigure.transaction.jta.JtaAutoConfiguration,\
org.springframework.boot.autoconfigure.validation.ValidationAutoConfiguration,\
org.springframework.boot.autoconfigure.web.DispatcherServletAutoConfiguration,\
org.springframework.boot.autoconfigure.web.EmbeddedServletContainerAutoConfiguration,\
org.springframework.boot.autoconfigure.web.ErrorMvcAutoConfiguration,\
org.springframework.boot.autoconfigure.web.HttpEncodingAutoConfiguration,\
org.springframework.boot.autoconfigure.web.HttpMessageConvertersAutoConfiguration,\
org.springframework.boot.autoconfigure.web.MultipartAutoConfiguration,\
org.springframework.boot.autoconfigure.web.ServerPropertiesAutoConfiguration,\
org.springframework.boot.autoconfigure.web.WebClientAutoConfiguration,\
org.springframework.boot.autoconfigure.web.WebMvcAutoConfiguration,\
org.springframework.boot.autoconfigure.websocket.WebSocketAutoConfiguration,\
org.springframework.boot.autoconfigure.websocket.WebSocketMessagingAutoConfiguration,\
org.springframework.boot.autoconfigure.webservices.WebServicesAutoConfiguration

# Failure analyzers
org.springframework.boot.diagnostics.FailureAnalyzer=\
org.springframework.boot.autoconfigure.diagnostics.analyzer.NoSuchBeanDefinitionFailureAnalyzer,\
org.springframework.boot.autoconfigure.jdbc.DataSourceBeanCreationFailureAnalyzer,\
org.springframework.boot.autoconfigure.jdbc.HikariDriverConfigurationFailureAnalyzer

# Template availability providers
org.springframework.boot.autoconfigure.template.TemplateAvailabilityProvider=\
org.springframework.boot.autoconfigure.freemarker.FreeMarkerTemplateAvailabilityProvider,\
org.springframework.boot.autoconfigure.mustache.MustacheTemplateAvailabilityProvider,\
org.springframework.boot.autoconfigure.groovy.template.GroovyTemplateAvailabilityProvider,\
org.springframework.boot.autoconfigure.thymeleaf.ThymeleafTemplateAvailabilityProvider,\
org.springframework.boot.autoconfigure.web.JspTemplateAvailabilityProvider

Redis相关装配类也在其中

org.springframework.boot.autoconfigure.data.redis.RedisAutoConfiguration,\
org.springframework.boot.autoconfigure.data.redis.RedisRepositoriesAutoConfiguration,\

其中RedisAutoConfiguration为主配置,至于第二个的话,没怎么仔细研究,看了下源代码是一个空类,没有具体实现

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

import java.net.URI;
import java.net.URISyntaxException;
import java.net.UnknownHostException;
import java.util.ArrayList;
import java.util.List;

import org.apache.commons.pool2.impl.GenericObjectPool;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPoolConfig;

import org.springframework.beans.factory.ObjectProvider;
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.data.redis.RedisProperties.Cluster;
import org.springframework.boot.autoconfigure.data.redis.RedisProperties.Sentinel;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.RedisClusterConfiguration;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.connection.RedisNode;
import org.springframework.data.redis.connection.RedisSentinelConfiguration;
import org.springframework.data.redis.connection.jedis.JedisConnection;
import org.springframework.data.redis.connection.jedis.JedisConnectionFactory;
import org.springframework.data.redis.core.RedisOperations;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.util.Assert;
import org.springframework.util.StringUtils;

/**
 * {@link EnableAutoConfiguration Auto-configuration} for Spring Data's Redis support.
 *
 * @author Dave Syer
 * @author Andy Wilkinson
 * @author Christian Dupuis
 * @author Christoph Strobl
 * @author Phillip Webb
 * @author Eddú Meléndez
 * @author Stephane Nicoll
 * @author Marco Aust
 */
@Configuration
@ConditionalOnClass({ JedisConnection.class, RedisOperations.class, Jedis.class })
@EnableConfigurationProperties(RedisProperties.class)
public class RedisAutoConfiguration {

   /**
    * Redis connection configuration.
    */
   @Configuration
   @ConditionalOnClass(GenericObjectPool.class)
   protected static class RedisConnectionConfiguration {

      private final RedisProperties properties;

      private final RedisSentinelConfiguration sentinelConfiguration;

      private final RedisClusterConfiguration clusterConfiguration;

      public RedisConnectionConfiguration(RedisProperties properties,
            ObjectProvider<RedisSentinelConfiguration> sentinelConfiguration,
            ObjectProvider<RedisClusterConfiguration> clusterConfiguration) {
         this.properties = properties;
         this.sentinelConfiguration = sentinelConfiguration.getIfAvailable();
         this.clusterConfiguration = clusterConfiguration.getIfAvailable();
      }

      @Bean
      @ConditionalOnMissingBean(RedisConnectionFactory.class)
      public JedisConnectionFactory redisConnectionFactory()
            throws UnknownHostException {
         return applyProperties(createJedisConnectionFactory());
      }

      protected final JedisConnectionFactory applyProperties(
            JedisConnectionFactory factory) {
         configureConnection(factory);
         if (this.properties.isSsl()) {
            factory.setUseSsl(true);
         }
         factory.setDatabase(this.properties.getDatabase());
         if (this.properties.getTimeout() > 0) {
            factory.setTimeout(this.properties.getTimeout());
         }
         return factory;
      }

      private void configureConnection(JedisConnectionFactory factory) {
         if (StringUtils.hasText(this.properties.getUrl())) {
            configureConnectionFromUrl(factory);
         }
         else {
            factory.setHostName(this.properties.getHost());
            factory.setPort(this.properties.getPort());
            if (this.properties.getPassword() != null) {
               factory.setPassword(this.properties.getPassword());
            }
         }
      }

      private void configureConnectionFromUrl(JedisConnectionFactory factory) {
         String url = this.properties.getUrl();
         if (url.startsWith("rediss://")) {
            factory.setUseSsl(true);
         }
         try {
            URI uri = new URI(url);
            factory.setHostName(uri.getHost());
            factory.setPort(uri.getPort());
            if (uri.getUserInfo() != null) {
               String password = uri.getUserInfo();
               int index = password.lastIndexOf(":");
               if (index >= 0) {
                  password = password.substring(index + 1);
               }
               factory.setPassword(password);
            }
         }
         catch (URISyntaxException ex) {
            throw new IllegalArgumentException("Malformed 'spring.redis.url' " + url,
                  ex);
         }
      }

      protected final RedisSentinelConfiguration getSentinelConfig() {
         if (this.sentinelConfiguration != null) {
            return this.sentinelConfiguration;
         }
         Sentinel sentinelProperties = this.properties.getSentinel();
         if (sentinelProperties != null) {
            RedisSentinelConfiguration config = new RedisSentinelConfiguration();
            config.master(sentinelProperties.getMaster());
            config.setSentinels(createSentinels(sentinelProperties));
            return config;
         }
         return null;
      }

      /**
       * Create a {@link RedisClusterConfiguration} if necessary.
       * @return {@literal null} if no cluster settings are set.
       */
      protected final RedisClusterConfiguration getClusterConfiguration() {
         if (this.clusterConfiguration != null) {
            return this.clusterConfiguration;
         }
         if (this.properties.getCluster() == null) {
            return null;
         }
         Cluster clusterProperties = this.properties.getCluster();
         RedisClusterConfiguration config = new RedisClusterConfiguration(
               clusterProperties.getNodes());

         if (clusterProperties.getMaxRedirects() != null) {
            config.setMaxRedirects(clusterProperties.getMaxRedirects());
         }
         return config;
      }

      private List<RedisNode> createSentinels(Sentinel sentinel) {
         List<RedisNode> nodes = new ArrayList<RedisNode>();
         for (String node : StringUtils
               .commaDelimitedListToStringArray(sentinel.getNodes())) {
            try {
               String[] parts = StringUtils.split(node, ":");
               Assert.state(parts.length == 2, "Must be defined as 'host:port'");
               nodes.add(new RedisNode(parts[0], Integer.valueOf(parts[1])));
            }
            catch (RuntimeException ex) {
               throw new IllegalStateException(
                     "Invalid redis sentinel " + "property '" + node + "'", ex);
            }
         }
         return nodes;
      }

      private JedisConnectionFactory createJedisConnectionFactory() {
         JedisPoolConfig poolConfig = this.properties.getPool() != null
               ? jedisPoolConfig() : new JedisPoolConfig();

         if (getSentinelConfig() != null) {
            return new JedisConnectionFactory(getSentinelConfig(), poolConfig);
         }
         if (getClusterConfiguration() != null) {
            return new JedisConnectionFactory(getClusterConfiguration(), poolConfig);
         }
         return new JedisConnectionFactory(poolConfig);
      }

      private JedisPoolConfig jedisPoolConfig() {
         JedisPoolConfig config = new JedisPoolConfig();
         RedisProperties.Pool props = this.properties.getPool();
         config.setMaxTotal(props.getMaxActive());
         config.setMaxIdle(props.getMaxIdle());
         config.setMinIdle(props.getMinIdle());
         config.setMaxWaitMillis(props.getMaxWait());
         return config;
      }

   }

   /**
    * Standard Redis configuration.
    */
   @Configuration
   protected static class RedisConfiguration {

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

      @Bean
      @ConditionalOnMissingBean(StringRedisTemplate.class)
      public StringRedisTemplate stringRedisTemplate(
            RedisConnectionFactory redisConnectionFactory)
                  throws UnknownHostException {
         StringRedisTemplate template = new StringRedisTemplate();
         template.setConnectionFactory(redisConnectionFactory);
         return template;
      }

   }

}

这个配置类在类级别上有3个注解

@Configuration
@ConditionalOnClass({ JedisConnection.class, RedisOperations.class, Jedis.class })
@EnableConfigurationProperties(RedisProperties.class)
@ConfigurationProperties(prefix = "spring.redis")
public class RedisProperties{
  ...
}

解释一下就是

​ 1.@Configuration:声明该类是一个配置类,会被Spring所加载并交由IoC容器进行管理

​ 2.@ConditionalOnClass:声明了当今当JedisConnection,RedisOperations,Jedis三个类已经存在于类路径上或者说这三个类所在的包已经被工程所引入的情况下进行加载

​ 3.@EnableConfigurationProperties:使用Spring boot的配置文件application.properties内相关属性对RedisProperties进行属性注入

​ 4.@ConfigurationProperties:读取application.properties内以spring.redis为前缀的属性注入到RedisProperties内

@ConditionalOnMissingBean(StringRedisTemplate.class)
@ConditionalOnMissingBean(RedisConnectionFactory.class)

配置类整体代码比较简单,不做过多解释,简要说明下几个注解的含义以及被注解方法的作用

​ 5.@ConditionalOnMissingBean:当spring上下文中不存在StringRedisTemplate实例会创建一个对应实例,若是已经显示定义了其实例,则不会被加载。

理解这些注解后,这个配置类的大意就可以了解了,如果检测到开发者引入了Redis相关配置

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>

这些Redis相关类会出现在类路径中,该配置类被激活,使用@Condition类型注解,来确保需要的Redis需要的相关实例都被实例化。

同时该配置了也提供了一个默认的RedisTemplate<K, V>实例——StringRedisTemplate 供我们使用。

Spring Boot对应自动配置做的确实挺好的,引入相关配置后,它会根据相应类是否出现在类路径中,来判断是否要配制出相应的组件,@Condition类型注解也就是Spring boot自动配置的关键注解

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 213,558评论 6 492
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 91,002评论 3 387
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 159,036评论 0 349
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 57,024评论 1 285
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 66,144评论 6 385
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 50,255评论 1 292
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 39,295评论 3 412
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 38,068评论 0 268
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 44,478评论 1 305
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 36,789评论 2 327
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 38,965评论 1 341
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 34,649评论 4 336
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 40,267评论 3 318
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 30,982评论 0 21
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 32,223评论 1 267
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 46,800评论 2 365
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 43,847评论 2 351

推荐阅读更多精彩内容