gpt4 book ai didi

java - spring boot配置具有不同文件名的外部化

转载 作者:行者123 更新时间:2023-12-01 22:47:35 25 4
gpt4 key购买 nike

我正在学习 Spring Boot 配置外部化。我希望我的应用程序从任何外部文件( /Users/<userid>/application.properties )读取配置。

我创建了 spring-web 项目,并添加了 spring.config.location=${user.home}进入 src/main/resource/application.properties

testConfig是我尝试通过 Controller 类中的以下代码访问的配置属性名称。

 @Value("${testConfig})
private String configValue;

我为 testConfig 指定了不同的值在不同的地方。

testConfig=InsideJarsrc/main/resources/application.properties文件。 testConfig=ApplicationRoot在项目根目录application.properties文件。
testConfig=homeDir在用户主目录 /User/<userid>/application.properties文件。

我如何运行该应用程序,结果是什么?

1. From different directory than project root  

Command: java -jar ../Downloads/first-springboot-app/target/first-springboot-app-0.0.1-SNAPSHOT.jar
-Dspring.config.location=file:/User/${LOGNAME}/application.properties
Result:InsideJar Expected result : homeDir

2. From Project root directory    

Command: java -jar target/first-springboot-app-0.0.1-SNAPSHOT.jar -Dspring.config.location=file:/Users/${LOGNAME}/application.properties

Result:applicationRootDirExpected result : homeDir

3. Added spring.config.name=application
4. Added spring.config.name=application.properties

Both of the above (3,4) gave same result .
Result:applicationRootDir Expected result : homeDir.

我已经浏览过以下链接和其他博客。
Springboot doc
SO , SO .

疑问/问题:为什么不从 homeDir 获取值 ( Users/<userid>/application.properties ) ?
任何帮助将不胜感激。

最佳答案

即使不添加spring.config.name,这也绝对应该按预期工作。 .

我运行了一个简单的 spring 应用程序,仅使用 web来自 start.spring.io 的依赖项并添加了 -Dspring.config.location=file:/Users/my-user/application.properties 。按预期工作。

然后我再次测试 -Dspring.config.location=file:/Users/${MY_USER}/application.properties并声明MY_USER=my-user ,这也有效。我这样做是为了测试环境变量是否也从路径本身读取。

话虽如此,您的配置存在问题,并且可能缺少一些小设置。我已经发布了我的代码 here因此,请随意查看并与您的进行比较。

希望有帮助,

干杯

关于java - spring boot配置具有不同文件名的外部化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58468109/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com