手寫一個springboot starter
阿新 • • 發佈:2021-12-15
springboot的starter的作用就是自動裝配。將配置類自動裝配好放入ioc容器裡。作為一個元件,提供給springboot的程式使用。
今天手寫一個starter。功能很簡單,呼叫starter內物件的一個方法輸出"hello! xxx"
先來了解以下命名規範
-
自定義 starter,工程命名格式為{xxx}-spring-boot-starter。
-
官方starter,工程命名格式為spring-boot-starter-{xxx}。
1.新建一個普通的maven工程,引入springboot依賴(2.5.6),專案名為hello-spring-boot-starter
pom.xml
<dependencies>
<!--很關鍵-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-configuration-processor</artifactId>
<optional>true</optional>
<version>2.5.6</version>
</dependency>
<!--springBoot-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-autoconfigure</artifactId>
<version>2.5.6</version>
</dependency>
<!-- Lombok-->
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>1.18.20</version>
</dependency>
</dependencies>
<!--打pom包的外掛-->
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.6.0</version>
<configuration>
<source>8</source>
<target>8</target>
</configuration>
</plugin>
</plugins>
</build>
2.編寫業務類HelloStarter
@Data //生成getset @AllArgsConstructor //生成有參構造器 public class HelloStarter { //業務類依賴的一些配置資訊,通過spring.properties配置 private HelloProperties helloProperties; public String hello() { return "hello! " + helloProperties.name; } }
3.編寫配置資訊類
@ConfigurationProperties(prefix = "com.shuai.hello") //繫結到spring.properties檔案中 @Data public class HelloProperties { String name; }
4. 編寫自動配置類,將所有物件注入到容器中。
@Configuration //表明這是一個springBoot的配置類 public class AutoConfiguration { @Bean //將物件放入IOC容器中,物件名就是方法名 public HelloProperties helloProperties(){ return new HelloProperties(); } @Bean //將物件放入IOC容器中,物件名就是方法名 public HelloStarter helloStarter(@Autowired HelloProperties helloProperties){ //自動注入 return new HelloStarter(helloProperties); } }
5.為了讓springboot容器掃描到配置類,建一個resource目錄,一個META-INF資料夾和spring.factories檔案
在spring.factories檔案中寫入
#等號後面是配置類的全路徑
org.springframework.boot.autoconfigure.EnableAutoConfiguration=com.config.AutoConfiguration
6.使用install打包到本地倉庫
注意:
所以一般我們使用install打包
7.匯入專案中進行測試<dependency> <groupId>com.shuai</groupId> <artifactId>hello-spring-boot-starter</artifactId> <version>1.0-SNAPSHOT</version> </dependency>使用starter中的物件
@RestController public class HelloController { @Autowired HelloStarter helloStarter; @RequestMapping("/hello") public String hello(){ return helloStarter.hello(); } }spring.properties中配置資訊
com.shuai.hello.name="starter"
訪問http://localhost:8080/hello 測試結果
非常棒!你現在已經會寫一個簡單的starter了,但是這遠遠不夠,後續還要加上@EnableConfigurationProperties,@EnableConfigurationProperties等註解,讓你的starter更加健壯
寄語:我們所要追求的,永遠不是絕對的正確,而是比過去的自己更好。