You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Spring Boot如何根据部署服务器加载对应目录的properties配置文件

解决方案

以下两种方案均适配你的目录结构与需求,可根据实际运维习惯选择:

方案1:启动参数指定配置(无代码侵入)

Spring Boot原生支持自定义配置搜索路径,无需修改代码,仅需在不同服务器的启动脚本中配置对应参数即可:

  • SERV-A e1 环境启动命令:
    java -jar your-app.jar --spring.config.location=classpath:/SERV-A/ --spring.profiles.active=e1
  • SERV-A e2 环境启动命令:
    java -jar your-app.jar --spring.config.location=classpath:/SERV-A/ --spring.profiles.active=e2
  • SERV-B e1 环境启动命令:
    java -jar your-app.jar --spring.config.location=classpath:/SERV-B/ --spring.profiles.active=e1
  • SERV-B e2 环境启动命令:
    java -jar your-app.jar --spring.config.location=classpath:/SERV-B/ --spring.profiles.active=e2

启动时会自动加载对应目录下的公共application.properties,再叠加子环境的配置文件,符合常规配置继承逻辑。

方案2:自动识别服务器适配(无需修改启动参数)

如果不想维护多套启动脚本,可在启动类中添加自动识别逻辑,同一jar包可直接在所有服务器启动:

步骤1:添加环境识别逻辑

将以下逻辑放在Spring Boot启动类main方法的最开头:

public static void main(String[] args) throws UnknownHostException {
    // 获取当前服务器hostname
    String hostName = InetAddress.getLocalHost().getHostName();
    String configDir = "";
    String activeProfile = "";

    // 匹配服务器类型与子环境
    if (hostName.contains("SERV-A")) {
        configDir = "classpath:/SERV-A/";
        activeProfile = hostName.contains("e1") ? "e1" : "e2";
    } else if (hostName.contains("SERV-B")) {
        configDir = "classpath:/SERV-B/";
        activeProfile = hostName.contains("e1") ? "e1" : "e2";
    }

    // 注入配置参数
    System.setProperty("spring.config.location", configDir);
    System.setProperty("spring.profiles.active", activeProfile);
    SpringApplication.run(YourApplication.class, args);
}

步骤2:验证配置加载

可通过注入配置值确认加载结果:

@Value("${你的配置项key}")
private String configValue;

注意事项

  • 确保打包时SERV-A、SERV-B目录被正常打入jar包,Maven项目可在pom.xml中添加以下配置避免目录被排除:
<build>
    <resources>
        <resource>
            <directory>src/main/resources</directory>
            <includes>
                <include>**/*</include>
            </includes>
        </resource>
    </resources>
</build>
  • 若存在classpath根目录的application.properties,spring.config.location指定路径下的配置优先级更高,不会和根目录配置冲突。

内容的提问来源于stack exchange,提问作者Akif

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.26 03:24:04