如何在普通代码中使用 application.yml 文件中的变量?

nol*_*te1 -1 java spring yaml spring-boot

例如,假设在我的 yml 文件中,我有一个名为指标的变量。并且基于指标变量的值是什么,我希望代码做一些不同的事情。我将如何访问常规代码中的 yml 变量并相应地使用它?

小智 7

你可以使用这个:

@Value("${your.path.yml.string}")
private String x;
Run Code Online (Sandbox Code Playgroud)

YML:

your:
  path:
    yml:
      string: hello
Run Code Online (Sandbox Code Playgroud)

x 将是“你好”

  • 哦好的。当我尝试时,我收到一条错误消息,指出通过字段“sampleService”表达的依赖关系未得到满足;嵌套异常是 org.springframework.beans.factory.BeanCreationException:创建名称为“sampleServiceImpl”的 bean 时出错:自动装配依赖项注入失败;嵌套异常是 java.lang.IllegalArgumentException:无法解析值“${indicator.string} 中的占位符“indicator.operation” (2认同)