【问题标题】:Declare list of objects in Spring application.properties file在 Spring application.properties 文件中声明对象列表
【发布时间】:2020-04-26 05:09:00
【问题描述】:

在 Spring Boot 应用程序中,我希望能够在我的 application.properties 文件中声明我的域对象列表,并将它们作为 List<TheDomainObject> 读取为 Bean

例如,假设我在application.properties 中有以下内容:

com.application.person.john.name=John Smith
com.application.person.john.home-directory=/Users/john.smith
com.application.person.john.private-key-file=/Users/john.smith/.ssh/id_rsa

com.application.person.adam.name=Adam Bell
com.application.person.adam.home-directory=/Users/adam.bell
com.application.person.adam.private-key-file=/Users/adam.bell/.ssh/id_rsa

etc

即我想将每个人的属性分组在一个键下。我可以添加任意数量的键(人)。

我不需要直接引用这些属性,但我想声明一个 Domain 对象如下(缩写):

class Person {
  String id;   (this would be the 'key', i.e. 'john', 'adam')
  String name;
  Path homeDirectory;
  Path privateKeyFile;

  // boilerplate
}

然后通过Configuration 接收List<Person>。自动化程度越高越好,但如果需要,我会非常乐意实现构建器或一些额外的转换器逻辑。

我找不到这种东西的任何文档,但我在 log4j 中看到过,例如,您可以在其中为任何包名称动态添加日志记录属性,所以它必须是可能的至少检索这些密钥。

我知道我可以以不同的方式执行此操作,例如使用 data.sql 导入脚本,但在我的情况下,将其保存在单个属性文件(或 yaml)格式中会非常理想。

【问题讨论】:

    标签: java spring spring-boot properties


    【解决方案1】:

    为什么不使用 id 作为显式属性?

    例如(yaml):

    com:
      application:
        persons:
          - 
            id: john
            name: John Smith
            home-directory: /Users/john.smith
          - 
            id: adam 
            name: Adam Bell
            home-directory: /Users/adam.bell
    

    这将在List<Person> persons; 中解决

    【讨论】:

    【解决方案2】:

    你为什么不使用@ConfigurationProperties 在这种情况下它会帮助你,对吧?

    详情请参考

    https://www.techiedelight.com/map-spring-boot-properties-to-pojo

    https://www.baeldung.com/configuration-properties-in-spring-boot

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-03-07
      • 1970-01-01
      • 2016-06-27
      • 1970-01-01
      相关资源
      最近更新 更多