Spring Boot+Gradle外部配置加载问题:@PropertySource找不到指定文件
解决Spring Boot + Gradle外部配置文件加载失败问题
问题根源
你犯了两个关键错误:
@PropertySource("file:remote-connection.properties")会让Spring在当前执行命令的工作目录查找文件,而非你通过spring.config.additional-location指定的目录,自然找不到目标文件。- 混淆了
spring.config.additional-location与@PropertySource的用法:前者是让Spring自动扫描指定目录/文件加载配置,后者是手动指定单个配置文件路径,两者无需同时使用。
正确解决方案
方案1:利用Spring Boot自动扫描特性(推荐)
Spring Boot会自动加载spring.config.additional-location指定目录下符合命名规范的配置文件(如application-*.properties或application.properties),无需手动用@PropertySource:
- 把外部的
remote-connection.properties改名为application-remote.properties(遵循Spring Boot的Profile命名规范) - 修改
build.gradle的bootRun配置,添加激活Profile的参数:
bootRun { args = [ "--spring.config.additional-location=file:/path/to/my/props/folder/", "--spring.profiles.active=remote" ] }
- 移除
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
相关产品推荐
相关产品推荐

