Springboot如何使用外部yml啟動
更新時間:2024年05月07日 15:04:26 作者:Spirit_NKlaus
這篇文章主要介紹了Springboot如何使用外部yml啟動問題,具有很好的參考價值,希望對大家有所幫助,如有錯誤或未考慮完全的地方,望不吝賜教
Springboot使用外部yml啟動
有時候我們想更靈活的使用配置文件,例如同一套代碼去部署多個客戶,此時差異大的地方其實只是配置文件,這是我們希望每次啟動項目從外部讀取配置文件來加載項目,你可以使用一些配置中心來實現(xiàn),當(dāng)然也可以自己定義外部文件來實現(xiàn)。
import com.ctrip.framework.apollo.Config; import com.ctrip.framework.apollo.ConfigChangeListener; import com.ctrip.framework.apollo.ConfigService; import com.ctrip.framework.apollo.model.ConfigChange; import com.ctrip.framework.apollo.model.ConfigChangeEvent; import lombok.extern.slf4j.Slf4j; import org.springframework.beans.factory.config.YamlPropertiesFactoryBean; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.boot.builder.SpringApplicationBuilder; import org.springframework.core.io.FileSystemResource; import java.util.Properties; import java.util.Set; @SpringBootApplication @Slf4j public class LitchiDaqApplication { private static Properties PROPERTIES = new Properties(); public static void main(String[] args) { // SpringApplication.run(LitchiDaqApplication.class, args); try { String filePath = System.getProperty("user.dir") + "/config" + "/application-daq.yml"; //此處獲取啟動參數(shù)中的config.id來判斷從哪里讀取config文件 String configId = System.getProperty("config.id"); if (configId != null) { //從Apollo配置中心獲取配置 Config config = ConfigService.getAppConfig(); //監(jiān)聽apollo配置修改 config.addChangeListener(new ConfigChangeListener() { @Override public void onChange(ConfigChangeEvent changeEvent) { log.info("發(fā)生改變的工作區(qū): {}", changeEvent.getNamespace()); for (String key : changeEvent.changedKeys()) { ConfigChange change = changeEvent.getChange(key); log.info(String.format("檢測到改變 - key: %s, oldValue: %s, newValue: %s, changeType: %s", change.getPropertyName(), change.getOldValue(), change.getNewValue(), change.getChangeType())); } } }); Set<String> keys = config.getPropertyNames(); for (String key : keys) { PROPERTIES.setProperty(key, config.getProperty(key, null)); } } else { YamlPropertiesFactoryBean factory = new YamlPropertiesFactoryBean(); factory.setResources(new FileSystemResource(filePath)); PROPERTIES = factory.getObject(); } } catch (Exception e) { log.error("項目初始化配置錯誤:", e); } new SpringApplicationBuilder(LitchiDaqApplication.class).properties(PROPERTIES).run(args); } }
項目模擬外部文件讀取
java -jar啟Spring boot項目使用外部yml
配置方式
java -jar xx.jar --spring.config.location=application.yml路徑
配置單一變量
java -jar xxx.jar --xxx=test
取值
spring的@value("${xxx}")
java -jar .\ydbanew-cases-2.4.16.1.jar -TZ=Asia/Shanghai -filterParam=2400 -appconfigServerUrl=http://172.18.12.239:8081/appconfig -appconfigServerCorp=2400 --server.port=64310
總結(jié)
以上為個人經(jīng)驗,希望能給大家一個參考,也希望大家多多支持腳本之家。
相關(guān)文章
Java使用TCP實現(xiàn)數(shù)據(jù)傳輸實例詳解
這篇文章主要介紹了Java使用TCP實現(xiàn)數(shù)據(jù)傳輸實例詳解的相關(guān)資料,需要的朋友可以參考下2017-06-06