SpringBoot如何啟動自動加載自定義模塊yml文件(PropertySourceFactory)
參考:https://deinum.biz/2018-07-04-PropertySource-with-yaml-files/
背景
自定義模塊時經(jīng)常會編寫當(dāng)前模塊的一些核心yml配置,如果要被Spring容器加載到通常的做法是將自定義模塊的yml命名為application-模塊名.yml
,比如db模塊命名為application-db.yml
,然后再在spring.profiles.include
中引入該db,即可加載到子模塊配置(前提是maven構(gòu)建時能夠?qū)esources資源目錄編譯進去)。
上面說的這種限制有很多,子模塊對于父模塊是黑箱操作,我們無法得知有多少個子模塊要被include進來,而且前綴必須以application開頭。
今天我們來看另外一種更加靈活的方式,自定義名稱的yml直接在子模塊中加載,各位朋友繼續(xù)往下看PropertySourceFactory
如何實現(xiàn)。
總結(jié)3步走
定義一個YamlPropertySourceFactory
,實現(xiàn)PropertySourceFactory
,重寫createPropertySource
方法
將接口給過來的資源流文件使用加載到spring
提供的YmlPropertiesFactorBean
中,由該工廠Bean
產(chǎn)出一個Properties
對象
將生成的Properties
對象傳入PropertiesPropertySource
中產(chǎn)出一個PropertySource
對象
import lombok.AllArgsConstructor; import org.springframework.beans.factory.config.YamlPropertiesFactoryBean; import org.springframework.core.env.PropertiesPropertySource; import org.springframework.core.env.PropertySource; import org.springframework.core.io.support.EncodedResource; import org.springframework.core.io.support.PropertySourceFactory; import java.io.FileNotFoundException; import java.io.IOException; import java.util.Properties; /** * @description: * @author: jianjun.ren * @date: Created in 2020/9/24 12:05 */ @AllArgsConstructor public class YamlPropertySourceFactory implements PropertySourceFactory { //這個方法有2個入?yún)ⅲ謩e為資源名稱和資源對象,這是第一步 public PropertySource< ? > createPropertySource(String name, EncodedResource resource) throws IOException { //這是第二步,根據(jù)流對象產(chǎn)出Properties對象 Properties propertiesFromYaml = loadYamlIntoProperties(resource); String sourceName = name != null ? name : resource.getResource().getFilename(); assert sourceName != null; //這是第三部,根據(jù)Properties對象,產(chǎn)出PropertySource對象,放入到Spring中 return new PropertiesPropertySource(sourceName, propertiesFromYaml); } private Properties loadYamlIntoProperties(EncodedResource resource) throws FileNotFoundException { try { YamlPropertiesFactoryBean factory = new YamlPropertiesFactoryBean(); factory.setResources(resource.getResource()); factory.afterPropertiesSet(); return factory.getObject(); } catch (IllegalStateException e) { Throwable cause = e.getCause(); if (cause instanceof FileNotFoundException) { throw (FileNotFoundException) e.getCause(); } throw e; } } }
創(chuàng)建咱們是說完了,小伙伴有很多問號,怎么去使用呢?
接下來我們再看康康:
在任意一個@Configuration
類中,你自己寫一個也可以,反正能夠被Spring
所掃描的
加入下面這段代碼,其實就一行:
@Configuration //這個地方的YamlPropertySourceFactory就是上面編寫的代碼類 @PropertySource(factory = YamlPropertySourceFactory.class, value = "classpath:xxx-xxx.yml") public class XXXXConfiguration { }
最后
好了到這里就結(jié)束了,去使用看看效果吧~
以上為個人經(jīng)驗,希望能給大家一個參考,也希望大家多多支持腳本之家。
相關(guān)文章
Spring Boot通過Junit實現(xiàn)單元測試過程解析
這篇文章主要介紹了Spring Boot通過Junit實現(xiàn)單元測試過程解析,文中通過示例代碼介紹的非常詳細,對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友可以參考下2020-01-01