【问题标题】:Spring boot not loading lists from two yaml filesSpring Boot 未从两个 yaml 文件加载列表
【发布时间】:2021-07-11 05:30:06
【问题描述】:

在春季,如果我们有两个 .yaml 文件。 (包含在 application.yaml 中)

application-one.yaml          application-two.yaml            
-------------------           ------------------- 
abc:                          abc:
 flow:                         flow:
    - id: 'remote02'            - id: 'remote04'
    - id: 'remote03'            - id: 'remote05'

如果这个配置的属性类是这样的-

@ConfigurationProperties(prefix = "abc")
class Abc {
    List<Flow> flow;
}

class Flow{
    String id;
}

然后将仅从一个文件加载“流”,即 flow.size() 给出 2。(remote04,remote05。这取决于 application.yaml 中的配置文件顺序)

但如果我将 yamls 文件更改为 -

application-one.yaml          application-two.yaml            
-------------------           ------------------- 
abc:                          abc:
 flow:                         flow:
    remote02:                     remote04:
       id: remote02                  id: remote04
    remote03:                     remote05:
       id: remote03                  id: remote05

和属性类

@ConfigurationProperties(prefix = "abc")
class Abc {
    HashMap<String, Flow> flow;
}

class Flow{
    String id;
}

现在 hashmap 将有 4 个条目。即 flow.size() 给出 4

那么这是否意味着 spring 不会从两个 yaml 中加载 List 结构并将它们添加到一起?

如果属实,如何克服这个限制?

【问题讨论】:

  • 我只是在这里猜测,但我认为这可能与 yaml 中的“一切都是地图”这一事实有关,但并非一切都是列表。所以列表是 1 个对象,它在 yaml 中具有相同的键,因此它被第一个或最后一个加载的“否决”(不确定是哪个)。但是,“地图”可以合并,因为无论如何这是默认行为。

标签: java spring spring-boot yaml


【解决方案1】:

我认为是因为 Spring boot transforms YAML files into properties。在第一种情况下,文件将像这样转换:

application-one.properties    application-two.properties
-------------------           ------------------- 
abc.flow[0].id=remote2        abc.flow[0].id=remote4
abc.flow[1].id=remote3        abc.flow[1].id=remote5

但在第二种情况下,你会得到

application-one.properties      application-two.properties
-------------------             ------------------- 
abc.flow.remote02.id=remote02   abc.flow.remote04.id=remote04                       
abc.flow.remote03.id=remote03   abc.flow.remote05.id=remote05

如您所见,在第一种情况下,您会得到两对相同的属性,而在第二种情况下,您会得到四个不同的属性。因此,在第一种情况下,两个属性将消失,因为它们是多余的。

我不确定您是否可以避免这种情况。上面链接的文档说您可以使用 YamlMapFactoryBean,但我对 Spring 的了解还不够,无法判断是否以及如何将其与 @ConfigurationProperties 结合使用。

【讨论】:

    猜你喜欢
    • 2016-04-06
    • 2016-10-24
    • 1970-01-01
    • 2015-12-14
    • 2015-11-06
    • 1970-01-01
    • 1970-01-01
    • 2021-04-15
    • 2016-10-28
    相关资源
    最近更新 更多