案例需求:自定义redis-stater。要求当导入redis坐标时,SpringBoot自动创建Jedis的Bean。
实现步骤:
1、创建redis-spring-boot-autoconfigure模块
2、创建redis-spring-boot-starter模块,依赖redis-spring-boot-autoconfigure的模块
3、在redis-spring-boot-autoconfigure模块中初始化Jedis的Bean。并定义META-INF/spring.factories文件。
1、创建两个项目:
2、在redis-spring-boot-stater依赖中引入configure
<dependency><groupId>com.itqiqi</groupId><artifactId>redis-spring-boot-autoconfigure</artifactId><version>0.0.1-SNAPSHOT</version></dependency>
3、在redis-spring-boot-autoconfigure模块依赖中引入jedis依赖
<dependency><groupId>redis.clients</groupId><artifactId>jedis</artifactId></dependency>
4、编写配置文件
@ConfigurationProperties(prefix = "redis")
//定义了属性配置的前缀,将来以redis开头的配置都对应RedisProperties类中的属性
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;}
}
5、在redis-spring-boot-autoconfigure模块中写核心的redis的自动配置类。实现自动装配
@Configuration
@EnableConfigurationProperties(RedisProperties.class)
public class RedisAutoConfiguration {//提供jedis的bean@Beanpublic Jedis jedis(RedisProperties redisProperties){return new Jedis(redisProperties.getHost(),redisProperties.getPort());}
}
6、在src/main/java/resources/META-INF/spring.factories文件中添加自动配置类路径
org.springframework.boot.autoconfigure.EnableAutoConfiguration=\com.itqiqi.redis.config.RedisAutoConfiguration
自定义的starter就创建完成。