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

Spring Boot如何从自定义路径读取application.properties文件

解决方案

方案1:通过代码指定默认配置位置

直接在Spring Boot启动阶段设置默认配置文件路径,打包成Jar后会优先加载该路径下的配置,无需额外命令行参数。

修改启动类代码:

@SpringBootApplication
public class DemoApp implements CommandLineRunner {

    public static void main(String[] args) {
        SpringApplication app = new SpringApplication(DemoApp.class);
        // 设置自定义配置文件路径,多路径可用逗号分隔
        app.setDefaultProperties(Collections.singletonMap(
            "spring.config.location", 
            "file:/user/demo/myAppProperties/application.properties"
        ));
        app.run(args);
    }

    @Override
    public void run(String... args) throws Exception {
        // 业务逻辑实现
    }
}

如果需要保留Jar内配置作为 fallback(外部配置未定义的属性仍使用Jar内值),可将spring.config.location替换为spring.config.additional-location,这样外部配置仅覆盖同名属性。

方案2:排除Jar内默认配置+@PropertySource加载外部配置

先修正Maven打包规则,确保Jar内不包含默认的application.properties,再通过注解加载外部配置。

步骤1:调整pom.xml打包配置

在build节点下添加资源排除规则,避免默认配置被打进Jar:

<build>
    <resources>
        <resource>
            <directory>src/main/resources</directory>
            <excludes>
                <exclude>application.properties</exclude>
            </excludes>
        </resource>
    </resources>
</build>

步骤2:修改启动类注解

添加ignoreResourceNotFound=true,避免外部配置文件不存在时启动失败:

@SpringBootApplication
@PropertySource(
    value = "file:/user/demo/myAppProperties/application.properties",
    ignoreResourceNotFound = true
)
public class DemoApp implements CommandLineRunner {

    public static void main(String[] args) {
        SpringApplication.run(DemoApp.class, args);
    }

    @Override
    public void run(String... args) throws Exception {
        // 业务逻辑实现
    }
}

注意:@PropertySource加载的配置优先级低于Spring Boot默认路径配置,因此必须确保Jar内无application.properties,否则会被覆盖。

方案3:内部配置指定外部路径(保留默认配置)

如果需要Jar内配置作为默认值,外部配置自动覆盖同名属性,只需在Jar内的application.properties中添加一行配置:

spring.config.additional-location=file:/user/demo/myAppProperties/

启动时Spring Boot会先加载Jar内配置,再加载指定路径下的application.properties,外部配置的同名属性会自动覆盖Jar内值,无需修改代码。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.14 17:42:15