【问题标题】:How to write a Spring Boot YAML configuration with nested JSON?如何使用嵌套 JSON 编写 Spring Boot YAML 配置?
【发布时间】:2017-10-07 04:15:14
【问题描述】:

我一直在使用带有 YAML 的 Spring Boot 应用程序进行外部配置,到目前为止效果很好。一个玩具例子:

@Component
@ConfigurationProperties
class MyConfig {
  String aaa;
  Foo foo;

  static class Foo {
    String bar;
  }
}

然后是具有以下属性的 yaml 文件:

aaa: hello
foo.bar: world

我的问题是我真的需要在我的配置中添加一个 JsonObject。我首先尝试将其作为字段添加到 MyConfig 类中,然后编写以下我认为在语法上有效的 YAML 文件:

aaa: hello
from:
  {
    "first_initial": "D",
    "last_initial": "E"
  }
foo.bar: world

Spring 抛出以下错误:Cannot access indexed value in property referenced...

我最终将值改为纯字符串,并使用 > 折叠标签将其放入 YAML,但这意味着我必须在我的代码中手动将字符串解析为 JsonObject。

有人知道怎么做吗?

【问题讨论】:

    标签: spring spring-boot yaml snakeyaml


    【解决方案1】:

    这应该可行:

    @Component
    @ConfigurationProperties
    class MyConfig {
      String aaa;
      Foo foo;
      String from;
      static class Foo {
        String bar;
      }
      // ... getters setters
    
      public JsonObject getFromAsJson() {
        // create object from "this.from"
      }
    }
    
    aaa: hello
    foo: 
      bar: world
    from: |
        {
          "first_initial": "D",
          "last_initial": "E"
        }
    

    还有这个:

    aaa: hello
    foo: 
      bar: world
    from: "{\"first_initial\": \"D\", \"last_initial\": \"E\"}"
    

    第一个版本会保留换行符。

    【讨论】:

    • 感谢您努力回答我的问题。我目前使用 > 字符将 JSON 视为字符串,但我真的很想将其保留为真正的 JSON,以利用编辑器语法突出显示和验证。该文档作为 YAML 文件进行验证,但 Spring 不喜欢将其作为配置文件读取。
    猜你喜欢
    • 2017-05-18
    • 2016-09-08
    • 1970-01-01
    • 2019-10-15
    • 1970-01-01
    • 2019-03-08
    • 2017-08-29
    • 2015-05-31
    相关资源
    最近更新 更多