Java 如何在.yml文件中使用属性占位符
我正在使用Java和spring boot。我想知道如何将属性占位符添加到Java 如何在.yml文件中使用属性占位符,java,spring-boot,yaml,manifest,string-interpolation,Java,Spring Boot,Yaml,Manifest,String Interpolation,我正在使用Java和spring boot。我想知道如何将属性占位符添加到.yml文件中。我发现了一些清晰的示例,但我不确定在哪里实例化了属性占位符。是否在系统环境变量、文件等中 Bootstrap.yml spring: cloud: config: username: ${my.stored.files.username} password: ${my.stored.files.password} label: ${spring.cloud.f
.yml
文件中。我发现了一些清晰的示例,但我不确定在哪里实例化了属性占位符。是否在系统环境变量、文件等中
Bootstrap.yml
spring:
cloud:
config:
username: ${my.stored.files.username}
password: ${my.stored.files.password}
label: ${spring.cloud.find.label}
uri: ${spring.cloud.config.uri}
enabled: false
failFast: true
用户正在使用属性占位符,但用户在哪里声明了它?
从中读取值的.yml在哪里?(问题同上)
是否有文档解释了连接
此web应用程序将使用“cf push”推送到cloud foundry,它将自动选择manifest.yml文件进行配置。如果可能的话,一个云铸造的例子将是伟大的
了解/Sample Application.properties文件
app.name=MyApp
app.description=${app.name}
用户能够使用${app.name},因为它已定义。我对上面的例子感到困惑。用户如何获取“${my.stored.files.username}”以及从何处获取“${my.stored.files.username}”。
这是在哪里定义的?我假设它是在system.properties或environment variables中。有人能证实吗?经过深入研究,我发现当我在.yml文件中使用占位符时,它会从environment variables中读取值。这在一开始是我理论的一部分,但没有人证实 针对当地环境的回答
spring:
cloud:
config:
username: ${my.stored.files.username}
password: ${my.stored.files.password}
label: ${spring.cloud.find.label}
uri: ${spring.cloud.config.uri}
enabled: false
failFast: true
*环境变量内*
然后
当您运行应用程序时,yml的读数是这样的
这就是解决我问题的环节
用于Cloudfoundry
您必须创建cups或手动将这些变量添加到服务中。如果是.yml文件,请使用{{your key}}}作为占位符。 SpringApplication从以下位置的application.properties文件加载属性,并将其添加到Spring环境中:
- 当前目录的/config子目录
- 当前目录
- 类路径/配置包
- 类路径根
$ java -jar myproject.jar --spring.config.name=myproject
以下示例显示了如何指定两个位置:
$ java -jar myproject.jar --spring.config.location=classpath:/default.properties,classpath:/override.properties
spring.config.name和spring.config.location很早就用于确定必须加载哪些文件。它们必须定义为环境属性(通常是OS环境变量、系统属性或命令行参数)
如果spring.config.location包含目录(与文件相反),则它们应该以/(并且在运行时,在加载之前附加从spring.config.name生成的名称,包括特定于概要文件的文件名).spring.config.location中指定的文件按原样使用,不支持特定于配置文件的变体,并由任何特定于配置文件的属性覆盖
配置位置按相反顺序搜索。默认情况下,配置的位置为classpath:/,classpath:/Config/,file:./,file:./Config/。生成的搜索顺序如下:
文件:./config/
文件:./
classpath:/config/
classpath://
文件:./custom config/
classpath:customconfig/
文件:./custom config/
classpath:customconfig/
文件:./config/
文件:./
classpath:/config/
classpath://
此搜索顺序允许您在一个配置文件中指定默认值,然后在另一个配置文件中有选择地覆盖这些值。您可以在application.properties(或使用spring.config.name选择的任何其他basename)中为应用程序提供默认值在其中一个默认位置。然后可以在运行时使用位于其中一个自定义位置的不同文件覆盖这些默认值。在进行一些研究和实验后,我发现占位符可以是环境变量和。属性文件的语法也适用于YAML文件。环境变量具有alr@Jesse已经解释过了。如果让我们说pass命令行参数:
--my.stored.files.username=UsernameSample
或--username=UsernameSample
,配置属性将按预期填充
my:
存储:
文件夹:
用户名:${username:defaultUsername}
我希望这可能对有类似问题的人有所帮助。请参阅:谢谢@DaveJarvis,但我不认为这是我想要的。您是否尝试过在YAML或应用程序使用的其他配置文件中搜索“用户名”?这可能对任何人来说都很困难
$ java -jar myproject.jar --spring.config.name=myproject
$ java -jar myproject.jar --spring.config.location=classpath:/default.properties,classpath:/override.properties