本文章記錄了SpringBoot如何自定義starter
一、首先創建啓動器
1、創建一個空的工程
2、建議對應的module,選擇maven來進行創建
定義對應的GroupId 和ArtifactId
定義對應的Module名稱
二、接下來創建springboot的初始化器,創建自動配置的相關的東西
1、新建module,選擇spring initializr來進行創建
創建後不引入任何模塊點擊next,創建生成
三、啓動器中引入自動配置模塊
刪除自動配置文件
刪除配置器多餘的依賴,只留下starter
四、創建自動配置類對應的Properties類
@ConfigurationProperties(prefix = "training.hello")
public class HelloProperties {
private String prefix;
private String suffix;
public String getPrefix() {
return prefix;
}
public void setPrefix(String prefix) {
this.prefix = prefix;
}
public String getSuffix() {
return suffix;
}
public void setSuffix(String suffix) {
this.suffix = suffix;
}
}
五、自定義測試的服務類
public class HelloService {
HelloProperties helloProperties;
public HelloProperties getHelloProperties() {
return helloProperties;
}
public void setHelloProperties(HelloProperties helloProperties) {
this.helloProperties = helloProperties;
}
public String sayHello(String name){
return helloProperties.getPrefix()+"-"+name+"-"+helloProperties.getSuffix();
}
}
六、定義自動配置類
@Configuration
@ConditionalOnWebApplication
@EnableConfigurationProperties(HelloProperties.class)
public class HelloAutoConfiguration {
@Autowired
HelloProperties helloProperties;
@Bean
public HelloService helloService(){
HelloService helloService = new HelloService();
helloService.setHelloProperties(helloProperties);
return helloService;
}
}
編寫完後需要在配置模塊中創建spring.factories並把自動配置類配置到配置文件中
META-INF/spring.factories
七、打包
分別將配置類和啓動類install,先執行配置類的install,然後執行啓動類的install,打包到本地
八、編寫測試工程,在工程中引入依賴
<dependency>
<groupId>com.training.starter</groupId>
<artifactId>training-spring-boot-starter</artifactId>
<version>1.0-SNAPSHOT</version>
</dependency>
編寫controller進行測試
@RestController
public class HelloController {
@Autowired
HelloService helloService;
@GetMapping("/hello")
public String Hello(){
return helloService.sayHello("AA");
}
}
在配置文件中添加外置屬性
training.hello.prefix="BB1"
training.hello.suffix="Hello Word"