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

Spring Boot+Gradle外部配置加载问题:@PropertySource找不到指定文件

解决Spring Boot + Gradle外部配置文件加载失败问题

问题根源

你犯了两个关键错误:

  1. @PropertySource("file:remote-connection.properties")会让Spring在当前执行命令的工作目录查找文件,而非你通过spring.config.additional-location指定的目录,自然找不到目标文件。
  2. 混淆了spring.config.additional-location与@PropertySource的用法:前者是让Spring自动扫描指定目录/文件加载配置,后者是手动指定单个配置文件路径,两者无需同时使用。

正确解决方案

方案1:利用Spring Boot自动扫描特性(推荐)

Spring Boot会自动加载spring.config.additional-location指定目录下符合命名规范的配置文件(如application-*.properties或application.properties),无需手动用@PropertySource:

  1. 把外部的remote-connection.properties改名为application-remote.properties(遵循Spring Boot的Profile命名规范)
  2. 修改build.gradle的bootRun配置,添加激活Profile的参数:
bootRun {
    args = [
            "--spring.config.additional-location=file:/path/to/my/props/folder/",
            "--spring.profiles.active=remote"
    ]
}
  1. 移除MyController上的@PropertySource注解,直接保留@Value注入即可:
@RestController
public class MyController {

    @Value("${remote.ip.address}")
    private String remoteIpAddress;
}

这样不管是用./gradlew bootRun还是java -jar命令运行,Spring都会自动从指定目录加载application-remote.properties。

方案2:保留自定义文件名(灵活性差,不推荐)

如果不想修改配置文件名,有两种方式:

  • 方式A:直接在spring.config.additional-location指定文件路径
    修改build.gradle:

    bootRun {
        args = [
                "--spring.config.additional-location=file:/path/to/my/props/folder/remote-connection.properties"
        ]
    }
    

    同样移除@PropertySource注解,Spring会自动加载这个指定文件。

  • 方式B:给@PropertySource指定完整路径
    这种方式硬编码了路径,仅适合临时场景:

    @RestController
    @PropertySource("file:/path/to/my/props/folder/remote-connection.properties")
    public class MyController {
    
        @Value("${remote.ip.address}")
        private String remoteIpAddress;
    }
    

为什么之前的尝试无效

  • @PropertySource("classpath:remote-connection.properties"):外部文件不在项目默认classpath目录(src/main/resources),因此无法被找到。
  • @PropertySource("remote-connection.properties"):默认从当前工作目录查找,而你执行./gradlew bootRun的工作目录是项目根目录,并非配置文件所在目录,所以找不到。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.21 16:46:07