非Spring Boot环境下如何在多服务器切换不同配置文件?
非Spring Boot环境下实现多服务器配置文件切换方案
方法1:通过JVM启动参数指定配置文件名
自己实现基于JVM参数的配置文件动态加载,启动时传入自定义参数区分环境,代码中读取参数拼接配置文件名:
// 读取JVM参数,设置默认值兜底 String profile = System.getProperty("config.profile", "default"); String configFileName = "application." + profile + ".properties"; // 加载配置文件(示例用Properties类,可替换成你当前的加载逻辑) Properties props = new Properties(); props.load(Thread.currentThread().getContextClassLoader().getResourceAsStream(configFileName));
启动命令示例:
# prd1服务器启动命令 java -Dconfig.profile=prd1 -jar your-web-app.jar # prd2服务器启动命令 java -Dconfig.profile=prd2 -jar your-web-app.jar
方法2:利用服务器环境变量区分
在两台服务器上分别设置专属环境变量,代码中读取环境变量匹配配置文件:
// 读取系统环境变量 String profile = System.getenv("APP_PROFILE"); // 无环境变量时用默认配置 if (profile == null || profile.trim().isEmpty()) { profile = "default"; } String configFileName = "application." + profile + ".properties"; // 后续加载逻辑同上
设置环境变量的方式:
- Linux:在应用启动脚本或
/etc/profile中添加export APP_PROFILE=prd1,执行source /etc/profile生效; - Windows:在系统环境变量中添加
APP_PROFILE=prd1,或启动脚本中用set APP_PROFILE=prd1。
方法3:根据服务器主机名/IP自动识别
让程序自动识别当前服务器的主机名或IP段,无需手动传参:
// 根据主机名判断 String hostname = InetAddress.getLocalHost().getHostName(); String profile; if ("prd1-server-hostname".equals(hostname)) { profile = "prd1"; } else if ("prd2-server-hostname".equals(hostname)) { profile = "prd2"; } else { profile = "default"; } // 或根据IP段判断 String ip = InetAddress.getLocalHost().getHostAddress(); if (ip.startsWith("10.0.1.")) { profile = "prd1"; } else if (ip.startsWith("10.0.2.")) { profile = "prd2"; }
方法4:指定外部配置文件路径
将配置文件放在服务器独立目录,启动时通过参数指定完整路径:
启动命令示例:
# prd1服务器 java -Dconfig.file=/opt/app-config/application.prd1.properties -jar your-web-app.jar # prd2服务器 java -Dconfig.file=/opt/app-config/application.prd2.properties -jar your-web-app.jar
代码中读取路径加载:
String configPath = System.getProperty("config.file", "application.default.properties"); Properties props = new Properties(); // 区分绝对路径和相对路径加载 if (new File(configPath).isAbsolute()) { props.load(new FileInputStream(configPath)); } else { props.load(Thread.currentThread().getContextClassLoader().getResourceAsStream(configPath)); }
内容的提问来源于stack exchange,提问作者Basar
相关产品推荐
相关产品推荐

