目录
- Springboot使用外部yml启动
- java -jar启Spring boot项目使用外部yml
- 配置方式
- 配置单一变量
- 取值
- 总结
Springboot使用外部yml启动
有时候我们想更灵活的使用配置文件,例如同一套代码去部署多个客户,此时差异大的地方其实只是配置文件,这是我们希望每次启动项目从外部读取配置文件来加载项目,你可以使用一些配置中心来实现,当然也可以自己定义外部文件来实现。
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";
//此处获取启动参数中的config.id来判断从哪里读取config文件
String configId = System.getProperty("config.id");
if (configId != null) {
//从Apollo配置中心获取配置
Config config = ConfigService.getAppConfig();
//监听apollo配置修改
config.addChangeListener(new ConfigChangeListener() {
@Override
public void onChange(ConfigChangeEvent changeEvent) {
log.info("发生改变的工作区: {}", 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
总结
以上为个人经验,希望能给大家一个参考,也希望大家多多支持。
声明:本站所有文章,如无特殊说明或标注,均为本站原创发布。任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站、书籍等各类媒体平台。如若本站内容侵犯了原著者的合法权益,可联系我们进行处理。

评论(0)