时间:2020-10-13 10:07:58 | 栏目:JAVA代码 | 点击:次
自定义Starter命名规则
注意artifactId的命名规则,Spring官方Starter通常命名为spring-boot-starter-{name}如 spring-boot-starter-web, Spring官方建议非官方Starter命名应遵循{name}-spring-boot-starter的格式, 如mybatis-spring-boot-starter。这里创建的项目的artifactId为helloworld-spring-boot-starter
开发Starter步骤
具体流程
创建配置类
@ConfigurationProperties 来定义配置的前缀
@EnableConfigurationProperties(InfluxdbProperties.class) @ConfigurationProperties(prefix = "spring.influxdb") public class InfluxdbProperties { private String username; public String getDatabase() { return database; } public void setDatabase(String database) { this.database = database; } }
编写自动配置类
@Configuration @Order(1) @EnableConfigurationProperties(InfluxdbProperties.class) @ConditionalOnClass(InfluxdbProperties.class) @ConditionalOnProperty(prefix = "spring.influxdb", value = "use-influxdb", havingValue="true" ,matchIfMissing = false) public class InfluxdbAutoConfiguration { private String scanEntitySuffix = "Entity.class"; @Bean @ConditionalOnMissingBean(AiInfluxdbTemplate.class) @Order(Ordered.HIGHEST_PRECEDENCE) public AiInfluxdbTemplate AiInfluxdbTemplate(InfluxdbProperties influxdbProperties){ return new AiInfluxdbTemplate(influxdbProperties); } }
编写spring.factories文件
Spring Boot会默认扫描跟启动类平级的包,如果我们的Starter跟启动类不在同一个主包下,需要通过配置spring.factories文件来生效
org.springframework.boot.autoconfigure.EnableAutoConfiguration=\ com.ai.base.boot.influxdb.InfluxdbAutoConfiguration