使用Spring Boot時,各個starter用起來非常方便踏枣。所以我們也可以把自己的一些組件項目封裝為starter聋溜,方便其他業(yè)務系統(tǒng)使用
添加依賴
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-autoconfigure</artifactId>
<version>2.1.6.RELEASE</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-configuration-processor</artifactId>
<version>2.1.6.RELEASE</version>
<optional>true</optional>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>1.18.8</version>
<optional>true</optional>
</dependency>
</dependencies>
屬性配置類
@Data
@ConfigurationProperties(prefix = "tenmao")
public class TenmaoProperties {
private boolean enabled;
private String name;
private String url;
private Set<String> hobbies;
}
核心服務類
public class TenmaoService {
private TenmaoProperties tenmaoProperties;
public TenmaoService(TenmaoProperties tenmaoProperties) {
this.tenmaoProperties = tenmaoProperties;
}
public void greeting() {
System.out.printf("tenmao: %s%n", tenmaoProperties);
}
}
自動配置類
@Configuration
@ConditionalOnClass({TenmaoService.class, TenmaoProperties.class})
@EnableConfigurationProperties({TenmaoProperties.class})
@ConditionalOnProperty(prefix = "tenmao", value = "enabled", matchIfMissing = true)
public class TenmaoAutoConfiguration {
private final TenmaoProperties tenmaoProperties;
@Autowired
public TenmaoAutoConfiguration(TenmaoProperties tenmaoProperties) {
this.tenmaoProperties = tenmaoProperties;
}
@Bean
@ConditionalOnMissingBean(TenmaoService.class)
public TenmaoService tenmaoService() {
return new TenmaoService(tenmaoProperties);
}
}
現(xiàn)在可以打包發(fā)布到maven倉庫給其他項目使用了
使用
使用方式如下:
- 添加依賴
<dependency>
<groupId>com.tenmao</groupId>
<artifactId>tenmao-spring-boot-starter</artifactId>
<version>1.0-SNAPSHOT</version>
</dependency>
- 配置信息(application.yml)
tenmao:
enabled: true
name: tenmao
url: http://www.reibang.com
hobbies:
- basketball
- football
- pingpong
- 直接注入就可以使用
@Resource
private TenmaoService tenmaoService;