spring引导不从两个yaml文件加载列表

cuxqih21  于 2021-07-14  发布在  Java
关注(0)|答案(1)|浏览(278)

在Spring,如果我们有两个.yaml文件(包含在应用程序中(yaml)

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

如果这个配置的properties类-

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

class Flow{
    String id;
}

然后只加载一个文件中的“flow”,即flow.size()给出2(远程04,远程05。这取决于配置文件在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个条目。i、 e.flow.size()给出4
所以这是否意味着spring不会从两个yaml加载列表结构并将它们添加到一起?
如果是真的,如何克服这个限制?

sr4lhrrt

sr4lhrrt1#

我认为这是因为springboot将yaml文件转换为属性。在第一种情况下,文件的转换方式如下:

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的了解还不够,还不知道你是否可以,如何把它和spring结合起来 @ConfigurationProperties .

相关问题