首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Spring :外部属性文件PropertySource

Spring :外部属性文件PropertySource
EN

Stack Overflow用户
提问于 2022-08-23 16:50:07
回答 1查看 197关注 0票数 0

我正在用gradle开发一个spring引导应用程序。

我想告诉spring在哪里使用参数读取.properties文件。因为我仍然通过gradle运行它,所以我将它添加到我的build.gradle

代码语言:javascript
复制
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

代码语言:javascript
复制
### remote-connection
remote.ip.address=127.0.0.1
remote.ip.port=5001

我正试着像这样装那些道具

代码语言:javascript
复制
@RestController
@PropertySource("file:remote-connection.properties")
public class MyController {

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

当我运行./gradlew bootRun时,我有以下错误

代码语言:javascript
复制
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之外,能够使用

代码语言:javascript
复制
java -jar my-application.jar --spring.config.additional-location=file:/path/to/my/props/folder/,file:/path/to/another/props/folder/

我遗漏了什么?

提前谢谢。

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2022-08-24 10:55:33

回答我自己的问题。

按照本指南https://mkyong.com/spring/spring-propertysources-example/,我已将运行args更改为

代码语言:javascript
复制
bootRun {
    args = [
            "--my.props.folder=/path/to/my/props/folder",
            "--my.other.props.folder=/path/to/another/props/folder",
    ]
}

像这样装道具

代码语言:javascript
复制
@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;
}

这样,就行了!!

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/73462443

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档