自定義springboot-start
阿新 • • 發佈:2022-05-08
一、 編寫starter
二、編寫測試類
------------------------------------------------------------
新建springboot專案,刪掉測試檔案,pom裡,只保留3個(自動配置,自動配置處理用來在yml提示),去掉build章節
<dependencies> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-autoconfigure</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-configuration-processor</artifactId> </dependency> </dependencies>
編寫HelloProperties
@ConfigurationProperties(prefix = "hello") public class HelloProperties { private String name = "anon"; private String address = "unname address";public String getName() { return name; } public void setName(String name) { this.name = name; } public String getAddress() { return address; } public void setAddress(String address) { this.address = address; } @Override public String toString() { return "HelloProperties{" + "name='" + name + '\'' + ", address='" + address + '\'' + '}'; } }
編寫自動配置類HelloServiceAutoConfiguration,
註解匯入上一個配置檔案,注意構造器注入屬性
@Configuration @EnableConfigurationProperties(HelloProperties.class) public class HelloServiceAutoConfiguration { private HelloProperties helloProperties; public HelloServiceAutoConfiguration(HelloProperties helloProperties) { this.helloProperties = helloProperties; } @Bean @ConditionalOnMissingBean public HelloService helloService(){ return new HelloService(helloProperties.getName(),helloProperties.getAddress()); } }
編寫業務方法HelloService,注意構造器
public class HelloService { private String name; private String address; public HelloService(String name, String address) { this.name = name; this.address = address; } public String sayHello(){ return "你好,我i是"+name+",來自"+address; } }
在resources裡,建立META-INF/spring.factories 檔案,讓springboot自動掃描啟動類
org.springframework.boot.autoconfigure.EnableAutoConfiguration=\
cn.taotao.config.HelloServiceAutoConfiguration
然後maven install到本地倉庫
---------------------------------------------------------
建立測試檔案 ,新建工程demo
新建測試類
@Autowired private HelloService helloService; @Test void hello(){ System.out.println("helloService.sayHello() = " + helloService.sayHello()); }
可以在application.yml 中測試注入的值