我正在使用 gradle 开发一个 Spring Boot 应用程序。
我很乐意告诉 spring 在哪里读取带有参数的
.properties
文件。由于我仍在通过 gradle 运行它,因此我已将其添加到我的 build.gradle
bootRun {
args = [
"--spring.config.additional-location=file:/path/to/my/props/folder/,file:/path/to/another/props/folder/"
]
}
进入
/path/to/my/props/folder/
我创建了一个文件remote-connection.properties
:
### remote-connection
remote.ip.address=127.0.0.1
remote.ip.port=5001
我正在尝试像这样加载这些道具
@RestController
@PropertySource("file:remote-connection.properties")
public class MyController {
@Value("${remote.ip.address}")
private String remoteIpAddress;
}
当我运行
./gradlew bootRun
时出现以下错误
org.springframework.beans.factory.BeanDefinitionStoreException: Failed to parse configuration class [my.package.MyApplication]; nested exception is java.io.FileNotFoundException: remote-connection.properties (No such file or directory)
(我也尝试过
@PropertySource("classpath:remote-connection.properties")
和@PropertySource("remote-connection.properties")
)
如果我将
remote-connection.properties
放入 src/main/resources
中,它可以完美地工作,但我希望该配置文件位于生成的 jar 之外,能够使用 运行它
java -jar my-application.jar --spring.config.additional-location=file:/path/to/my/props/folder/,file:/path/to/another/props/folder/
我错过了什么?
回答我自己的问题。
遵循本指南https://mkyong.com/spring/spring-propertysources-example/我已将运行参数更改为
bootRun {
args = [
"--my.props.folder=/path/to/my/props/folder",
"--my.other.props.folder=/path/to/another/props/folder",
]
}
并像这样加载道具
@RestController
@PropertySource("file:${my.props.folder}/remote-connection.properties")
@PropertySource("file:${my.other.props.folder}/some-more.properties")
public class MyController {
@Value("${remote.ip.address}")
private String remoteIpAddress;
}
这样就可以了!!