您好,登錄后才能下訂單哦!
這篇文章主要介紹了怎么定義一個spring boot starter,具有一定借鑒價值,感興趣的朋友可以參考下,希望大家閱讀完這篇文章之后大有收獲,下面讓小編帶著大家一起了解一下。
一、建立模塊
名稱規(guī)范:XXX-spring-boot-starter
二、編寫B(tài)ean
public class BeanConfig { @Bean TestBean testBean(){ TestBean testBean = new TestBean(); return testBean; } }
這里我們有一個BeanConfig類,通過它去注入一些Bean
三、將BeanConfig交給Spring容器
編寫spring.factories: 創(chuàng)建resources\META-INF\spring.factories文件
org.springframework.boot.autoconfigure.EnableAutoConfiguration=com.config.BeanConfig
那么在啟動時會通過AutoConfigurationImportSelector將BeanConfig注入到容器中。
四、打jar,生成maven依賴(略)
導(dǎo)入依賴即可以生效了。
如果想自定義一些配置怎么去做?
編寫配置類:
@ConfigurationProperties("com.test") // 需要配合@EnableConfigurationProperties使用 public class BeanProperties { private String testName = "default-name"; private Long telephoneNumber; // 必須有set方法 public void setTestName(String testName) { this.testName = testName; } public void setTelephoneNumber(Long telephoneNumber) { this.telephoneNumber = telephoneNumber; } @PostConstruct void init(){ String name = this.testName; System.out.println("-----------------------------"+name); Long telephoneNumber = this.telephoneNumber; System.out.println("-----------------------------"+telephoneNumber); } }
其中的@ConfigurationProperties注解要和@EnableConfigurationProperties搭配使用(實際也是一個EnableConfigurationPropertiesRegistrar)
那么在BeanConfig上添加注解:@EnableConfigurationProperties(BeanProperties.class)
@EnableConfigurationProperties(BeanProperties.class) public class BeanConfig { @Bean TestBean testBean(){ TestBean testBean = new TestBean(); return testBean; } }
項目中引入依賴后,只需要在配置文件中指定值就可以了,這里的前綴要和@ConfigurationProperties指定的值相同
#com.test.test-name=zhangsan com.test.telephone-number=12300000000
不指定則使用定義的默認值:
-----------------------------default-name -----------------------------12300000000
當(dāng)然,@ConfigurationProperties注解也不一定要和@EnableConfigurationProperties搭配使用,前提是spring容器要知道你的@ConfigurationProperties配置類
修改BeanConfig類,將注解改為@Import(BeanProperties.class)也是有效的。
@Import(BeanProperties.class) public class BeanConfig { @Bean TestBean testBean(){ TestBean testBean = new TestBean(); return testBean; } }
如果不通過SPI方式導(dǎo)入怎么做?
還是@Import注解方式,首先自定義注解:
@Target({java.lang.annotation.ElementType.TYPE}) @Retention(RetentionPolicy.RUNTIME) @Import({BeanConfig.class}) public @interface StarterAnnotation { }
這里Import導(dǎo)入了BeanConfig
然后項目中啟動類加上注解@StarterAnnotation即可。
感謝你能夠認真閱讀完這篇文章,希望小編分享的“怎么定義一個spring boot starter”這篇文章對大家有幫助,同時也希望大家多多支持億速云,關(guān)注億速云行業(yè)資訊頻道,更多相關(guān)知識等著你來學(xué)習(xí)!
免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進行舉報,并提供相關(guān)證據(jù),一經(jīng)查實,將立刻刪除涉嫌侵權(quán)內(nèi)容。