springboot加載外部配置文件實踐(properties、yml)
1.前言
通過PropertySourceLoader接口的實現(xiàn)類配合監(jiān)聽器實現(xiàn)加載外部的配置文件,加載properties文件使用PropertiesPropertySourceLoader,加載yml文件使用YamlPropertySourceLoader。
通過監(jiān)聽器將配置文件加載到Spring環(huán)境配置中,且可以指定優(yōu)先級。
核心是將配置文件加載PropertySource中并將其添加到spring的MutablePropertySources中,使其可以通過@value等方式獲取配置文件中的屬性值。
2.加載properties文件
1.方法一:PropertiesPropertySourceLoader
public class MyApplicationContextInitializer implements ApplicationContextInitializer {
@Override
public void initialize(ConfigurableApplicationContext configurableApplicationContext) {
PropertiesPropertySourceLoader loader = new PropertiesPropertySourceLoader();
try {
PropertySource<?> propertySource = loader.load("publicConfiguration", new InputStreamResource(Files.newInputStream(Paths.get("C:\\Users\\fkp12\\Desktop\\application.properties")))).get(0);
configurableApplicationContext.getEnvironment().getPropertySources().addFirst(propertySource);
} catch (IOException e) {
throw new RuntimeException(e);
}
}
}
2.方法二:PropertiesFactoryBean
public class MyApplicationContextInitializer implements ApplicationContextInitializer {
@Override
public void initialize(ConfigurableApplicationContext configurableApplicationContext) {
PropertiesFactoryBean factoryBean = new PropertiesFactoryBean();
try {
factoryBean.setLocation(new InputStreamResource(Files.newInputStream(Paths.get("C:\\Users\\fkp12\\Desktop\\application.properties"))));
Properties object = factoryBean.getObject();
if(object != null){
PropertiesPropertySource propertySource = new PropertiesPropertySource("publicConfiguration",object);
configurableApplicationContext.getEnvironment().getPropertySources().addFirst(propertySource);
}
} catch (IOException e) {
throw new RuntimeException(e);
}
}
}
3.加載yml文件
1.方法一:YamlPropertySourceLoader
public class MyApplicationContextInitializer implements ApplicationContextInitializer {
@Override
public void initialize(ConfigurableApplicationContext configurableApplicationContext) {
YamlPropertySourceLoader loader = new YamlPropertySourceLoader();
try {
PropertySource<?> propertySource = loader.load("externalConfiguration", new InputStreamResource(Files.newInputStream(Paths.get("C:\\Users\\fkp12\\Desktop\\application.yml")))).get(0);
configurableApplicationContext.getEnvironment().getPropertySources().addFirst(propertySource);
} catch (IOException e) {
throw new RuntimeException(e);
}
}
}
2.方法二:YamlPropertiesFactoryBean
public class MyApplicationContextInitializer implements ApplicationContextInitializer {
@Override
public void initialize(ConfigurableApplicationContext configurableApplicationContext) {
YamlPropertiesFactoryBean factoryBean = new YamlPropertiesFactoryBean();
try {
factoryBean.setResources(new InputStreamResource(Files.newInputStream(Paths.get("C:\\Users\\fkp12\\Desktop\\application.yml"))));
Properties object = factoryBean.getObject();
if(object != null){
PropertiesPropertySource propertySource = new PropertiesPropertySource("publicConfiguration",object);
configurableApplicationContext.getEnvironment().getPropertySources().addFirst(propertySource);
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
4.配置優(yōu)先級
通過上述代碼可以發(fā)現(xiàn)所有方法最后都是通過configurableApplicationContext.getEnvironment().getPropertySources().addFirst(propertySource)將封裝好的PropertySource對象加入到Spring配置中的,而都是通過調(diào)用addFirst(PropertySource propertySource),除了addFirst還有addLast,addBefore,addAfter,這就與優(yōu)先級有關(guān)系了,先說一下addBefore和addAfter,這兩個方法參數(shù)都是String relativePropertySourceName, PropertySource<?> propertySource,意思就是要將此propertySource添加在名為relativePropertySourceName的propertySource的前邊還是后邊,放在前邊的在讀取屬性時會優(yōu)先讀取屬性值,而addFirst和addLast則是將此propertySource放在整個列表的最前或最后。
對于優(yōu)先讀取該屬性的值的解釋
例如項目中的配置文件application.yml中有屬性name: zhangsan,外部配置文件externalApplication.yml中有屬性name: lisi,通過上述任何方式將外部配置文件加載到Spring配置中后因為兩個配置文件中都有name屬性,但其值不相同,這個時候如果通過@Value("${name}")取值會取到zhangsan還是lisi呢,答案是在上述PropertySource列表中靠前的會優(yōu)先生效。
如果想讓外部的配置文件優(yōu)先則可以使用addFirst方法添加propertySource。
提到配置文件的優(yōu)先級就想起了springboot默認讀取配置文件的優(yōu)先級,參考下方說明:
優(yōu)先級依次遞減
- 1.在執(zhí)行命令的目錄下建config文件夾,然后把配置文件放到這個文件夾下。(在jar包的同一個目錄下建config文件夾,執(zhí)行命令需要在jar包所在目錄下才行)
- 2.直接把配置文件放到j(luò)ar包的同級目錄
- 3.在classpath下建一個config文件夾,然后把配置文件放進去。
- 4.在classpath下直接放配置文件。
5.使用的監(jiān)聽器以及加載的時機(監(jiān)聽的事件)
無論使用那種監(jiān)聽器的實現(xiàn)類型,都需要拿到ConfigurableEnvironment這個參數(shù),可以在多個時機加載配置文件,例如environmentPrepared,contextPrepared,下面展示三種方式實現(xiàn)
方法一:
public class MyApplicationContextInitializer implements ApplicationContextInitializer {
@Override
public void initialize(ConfigurableApplicationContext configurableApplicationContext) {
YamlPropertySourceLoader loader = new YamlPropertySourceLoader();
try {
PropertySource<?> propertySource = loader.load("externalConfiguration", new InputStreamResource(Files.newInputStream(Paths.get("C:\\Users\\fkp12\\Desktop\\application.yml")))).get(0);
configurableApplicationContext.getEnvironment().getPropertySources().addFirst(propertySource);
} catch (IOException e) {
throw new RuntimeException(e);
}
}
}需要將該類的全限定名配置到spring.factories中
org.springframework.context.ApplicationContextInitializer=com.fkp.springboot_listener.listener.MyApplicationContextInitializer
方法二:
public class MySpringApplicationRunListener implements SpringApplicationRunListener {
private final SpringApplication springApplication;
private final String[] args;
public MySpringApplicationRunListener(SpringApplication springApplication, String[] args) {
this.springApplication = springApplication;
this.args = args;
}
@Override
public void starting(ConfigurableBootstrapContext bootstrapContext) {
System.out.println("SpringApplicationRunListener....starting");
}
@Override
public void environmentPrepared(ConfigurableBootstrapContext bootstrapContext, ConfigurableEnvironment environment) {
YamlPropertySourceLoader loader = new YamlPropertySourceLoader();
try {
PropertySource<?> propertySource = loader.load("externalConfiguration", new InputStreamResource(Files.newInputStream(Paths.get("C:\\Users\\fkp12\\Desktop\\application.yml")))).get(0);
environment.getPropertySources().addFirst(propertySource);
} catch (IOException e) {
throw new RuntimeException(e);
}
}
@Override
public void contextPrepared(ConfigurableApplicationContext context) {
System.out.println("SpringApplicationRunListener....contextPrepared");
}
@Override
public void contextLoaded(ConfigurableApplicationContext context) {
System.out.println("SpringApplicationRunListener....contextLoaded");
}
@Override
public void started(ConfigurableApplicationContext context) {
System.out.println("SpringApplicationRunListener....started");
}
@Override
public void running(ConfigurableApplicationContext context) {
System.out.println("SpringApplicationRunListener....running");
}
@Override
public void failed(ConfigurableApplicationContext context, Throwable exception) {
System.out.println("SpringApplicationRunListener....failed");
}
}
需要將該類的全限定名配置到spring.factories中
org.springframework.boot.SpringApplicationRunListener=com.fkp.springboot_listener.listener.MySpringApplicationRunListener
方法三:
public class MyApplicationListener implements ApplicationListener<ApplicationEnvironmentPreparedEvent> {
@Override
public void onApplicationEvent(ApplicationEnvironmentPreparedEvent applicationEnvironmentPreparedEvent) {
YamlPropertySourceLoader loader = new YamlPropertySourceLoader();
try {
PropertySource<?> propertySource = loader.load("externalConfiguration", new InputStreamResource(Files.newInputStream(Paths.get("C:\\Users\\fkp12\\Desktop\\application.yml")))).get(0);
applicationEnvironmentPreparedEvent.getEnvironment().getPropertySources().addFirst(propertySource);
} catch (IOException e) {
throw new RuntimeException(e);
}
}
}需要將該類的全限定名配置到spring.factories中
org.springframework.context.ApplicationListener=com.fkp.springboot_listener.listener.MyApplicationListener
備注:通過Environment取Spring配置中的值
Environment或?qū)崿F(xiàn)該接口的類可以通過多種方式獲取,例如上述ApplicationEnvironmentPreparedEvent#getEnvironment()獲取ConfigurableEnvironment
通用的一種方法是通過ApplicationContext獲取,ApplicationContext#getEnvironment(),ApplicationContext可以從Spring容器中取。
通過Environment的getProperty方法可以取Spring配置中屬性的值。
總結(jié)
以上為個人經(jīng)驗,希望能給大家一個參考,也希望大家多多支持腳本之家。
相關(guān)文章
SpringBoot配置加載,各配置文件優(yōu)先級對比方式
這篇文章主要介紹了SpringBoot配置加載,各配置文件優(yōu)先級對比方式,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2021-08-08
常用json與javabean互轉(zhuǎn)的方法實現(xiàn)
這篇文章主要介紹了常用json與javabean互轉(zhuǎn)的方法實現(xiàn),文中通過示例代碼介紹的非常詳細,對大家的學(xué)習或者工作具有一定的參考學(xué)習價值,需要的朋友們下面隨著小編來一起學(xué)習學(xué)習吧2021-04-04
解決spirngboot連接redis報錯:READONLY?You?can‘t?write?against?
docker部署的redis,springboot基本每天來連redis都報錯:READONLY?You?can't?write?against?a?read?only?replica,重啟redis后,可以正常連接。但是每天都重啟redis,不現(xiàn)實,也很麻煩,今天給大家分享解決方式,感興趣的朋友一起看看吧2023-06-06
五種SpringBoot實現(xiàn)數(shù)據(jù)加密存儲的方式總結(jié)
這篇文章主要為大家詳細介紹了五種常見數(shù)據(jù)加密存儲的方法(結(jié)合SpringBoot和MyBatisPlus框架進行實現(xiàn)),文中的示例代碼講解詳細,需要的可以參考下2023-11-11
關(guān)于Jsoup將相對路徑轉(zhuǎn)為絕對路徑的方法
這篇文章主要介紹了關(guān)于Jsoup將相對路徑轉(zhuǎn)為絕對路徑的方法,jsoup 是一款Java 的HTML解析器,可直接解析某個URL地址、HTML文本內(nèi)容,需要的朋友可以參考下2023-04-04
HttpClient的DnsResolver自定義DNS解析另一種選擇深入研究
這篇文章主要為大家介紹了HttpClient的DnsResolver自定義DNS解析另一種選擇深入研究,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進步,早日升職加薪2023-10-10

