Spring Boot中starter的原理是什么?如何实现一些starter?
原理:核心就是@EnableAutoConfiguration注解,在该注解中有一个@Import注解。@Import注解导入了配置类:AutoConfigurationImportSelector.class。在该类中使用SpringFactoriesLoader.class加载配置文件META-INF/spring.factories。
实现也starter需要实现一下步骤:
- autoconfigure模块
- 实现RedisAutoConfiguration.class
- 实现RedisProperties.class
- 实现配置文件META-INF/spring.factories
- 实现starter模块
只需要在starter模块的pom文件中引入autoconfigure模块的依赖即可。
RedisAutoConfiguration.class
@Configuration
@EnableConfigurationProperties(RedisProperties.class)
public class RedisAutoConfiguration {
@Bean
@ConditionalOnMissingBean(name = "jedis")
public Jedis jedis(RedisProperties redisProperties){
System.out.println("RedisAutoConfiguraton...");
return new Jedis(redisProperties.getHost(), redisProperties.getPort());
}
}
RedisProperties.class
@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;
}
}
META-INF/spring.factories
org.springframework.boot.autoconfigure.EnableAutoConfiguration=\
com.itheima.redis.config.RedisAutoConfiguration