04、SpringBoot自动配置-自定义starter
①创建 redis-spring-boot-autoconfigure 模块
②创建 redis-spring-boot-starter 模块,依赖 redis-spring-boot-autoconfigure的模块
③在 redis-spring-boot-autoconfigure 模块中初始化 Jedis 的 Bean。并定义META-INF/spring.factories 文件
④在测试模块中引入自定义的 redis-starter 依赖,测试获取 Jedis 的Bean,操作 redis。
创建redis-spring-boot-starter工程:
该工程仅用来聚合redis-spring-boot-autoconfigure工程pom文件中引入redis-spring-boot-autoconfigure坐标:
<!--引入configure--> <dependency> <groupId>com.itheima</groupId> <artifactId>redis-spring-boot-autoconfigure</artifactId> <version>0.0.1-SNAPSHOT</version> </dependency>
创建redis-spring-boot-autoconfigure配置工程:
创建RedisProperties配置文件参数绑定类:
package com.itheima.redis.config; import org.springframework.boot.context.properties.ConfigurationProperties; @ConfigurationProperties(prefix = "redis") public class RedisProperties { private String host = "localhost"; private int port = 6379; public String getHost() { return host; } public void setHost(String host) { this.host = host; } public int getPort() { return port; } public void setPort(int port) { this.port = port; } }
创建RedisAutoConfiguration自动配置类:
package com.itheima.redis.config; import org.springframework.boot.autoconfigure.condition.ConditionalOnClass; import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean; import org.springframework.boot.context.properties.EnableConfigurationProperties; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import redis.clients.jedis.Jedis; @Configuration @EnableConfigurationProperties(RedisProperties.class) @ConditionalOnClass(Jedis.class) public class RedisAutoConfiguration { /** * 提供Jedis的bean */ @Bean @ConditionalOnMissingBean(name = "jedis") public Jedis jedis(RedisProperties redisProperties) { System.out.println("RedisAutoConfiguration...."); return new Jedis(redisProperties.getHost(), redisProperties.getPort()); } }
在resource目录下创建META-INF文件夹并创建spring.factories:
org.springframework.boot.autoconfigure.EnableAutoConfiguration=\
com.itheima.redis.config.RedisAutoConfiguration
在springboot-enable工程中引入自定义的redis的starter:
<!--自定义的redis的starter--> <dependency> <groupId>com.itheima</groupId> <artifactId>redis-spring-boot-starter</artifactId> <version>0.0.1-SNAPSHOT</version> </dependency>
测试:
Jedis jedis = context.getBean(Jedis.class); System.out.println(jedis);