javascript
Spring Boot自定义starter
一、創建starter的原理
在我們使用spring Boot的時候,常常要引入很多的starter,這也是spring Boot的一大特色,那么這些stater到底時怎么回事兒呢,今天就一起扒開看看
引入starter --- xxxAutoConfiguration --- 容器中放入組件 ---- 綁定xxxProperties ---- 配置項
yang-hello-spring-boot-starter(啟動器)
yang-hello-spring-boot-starter-autoconfigure(自動配置包)
二、自定義starter步驟
在創建自定義stater的時候,我們需要兩個工程,第一個就是場景啟動器,也就是xxx-spring-boot-stater;建個普通maven工程就可以了;在該項目中的pom文件中將自動配置包坐標引入,要是還需要其他的也可以引入
<?xml version="1.0" encoding="UTF-8"?> <project xmlns="http://maven.apache.org/POM/4.0.0"xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"><modelVersion>4.0.0</modelVersion><groupId>com.yang</groupId><artifactId>yang-spring-boot-stater</artifactId><version>1.0-SNAPSHOT</version><properties><maven.compiler.source>8</maven.compiler.source><maven.compiler.target>8</maven.compiler.target></properties><dependencies><!--引入自動配置包--><dependency><groupId>com.yang</groupId><artifactId>yang-spring-boot-stater-autoconfigure</artifactId><version>0.0.1-SNAPSHOT</version></dependency></dependencies></project>?2.之后,我們要準備自動配置包,需要創建一個springBoot項目,然后在pom文件中引入自己需要的依賴,建議引入spring-boot-configuration-processor這樣其他項目使用配置的時候就由提示了
3.創建一個bean即我們看到官方使用的xxxProperties,將其與配置文件綁定
//指定配置文件的前綴 @ConfigurationProperties(prefix = "yang.hello") @Data public class HelloProperties {private String prefix;private String suffix;}4.創建一個service,模擬業務代碼邏輯,默認不要將其放入容器中,后面我們使用配置文件同一管理
public class HelloService {//自動注入了實體類helloProperties,所以修改配置類的時候,屬性就會跟著修改@AutowiredHelloProperties helloProperties;public String hello(String username){return helloProperties.getPrefix()+username+helloProperties.getSuffix();} }? ? ? ?5.?之后還要準備一個配置類,將service注入容器中(因為在第一步的service中我們不會將其? ? ? ? ? ? ? ? ?注入容器);并且使用EnableConfigurationProperties注解,將實體類和配置文件的關聯打? ? ? ? ? ? ? 開以及注入容器;還可以使用ConditionOnMissingBean等注解,按照具體情況進行條件判斷
/*** @ProjectName: com.yang.yangspringbootstaterautoconfigure.conf* @author: ZhangBiBo* @description: 配置類,打開實體類和properties的關聯,并將其注入容器,當容器中沒有helloService實體類的時候自動配置,若有就按照用戶的來* @data: 2022/3/14*/ @EnableConfigurationProperties(HelloProperties.class) @Configuration public class YangAutoConfiguration {@ConditionalOnMissingBean(HelloService.class)@Beanpublic HelloService helloService(){HelloService helloService = new HelloService();return helloService;} }6.最后需要在resource目錄下建立一個META-INF目錄,創建spring.faction文件,將我們的配置類? ? ?XXXAutoConfiguration類的類路徑放入其中,這樣在springBoot在啟動時就可以加載到我們自定? ? ?義的配置類了,否則的話加載不到配置類,也就找不到文件了
?7.最后將場景啟動器和自動配置包install就可使用;我們可以重新創建一個工程來進行測試,引入場景啟動器,直接Autowired引入我們剛剛的HelloService即可,之后在application.yaml中配置好需要配置的文件
總結
以上是生活随笔為你收集整理的Spring Boot自定义starter的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 联通短消息服务器域名,中国联通域名服务器
- 下一篇: SpringBoot 文件管理微服务 支