将yml中的列表映射到Scala中的对象列表(Spring Boot)

时间:2019-03-04 09:50:34

标签: java spring scala

背景

我已经阅读了一些示例,内容涉及如何使用ConfigurationProperties从配置中读取列表。请参见下文

  1. Mapping list in Yaml to list of objects in Spring Boot
  2. https://github.com/konrad-garus/so-yaml
  3. https://www.boraji.com/spring-boot-configurationproperties-example

..以及更多。


我无法在 Scala 中实现此功能。我想从application.yml获取组织列表(ID和名称),但是它总是返回一个空列表。

application.yml

org-registry-list:
  organisations:
    -
      orgId: 1
      orgName: "Google"
    -
      orgId: 20
      orgName: "Microsoft"

这是我在Scala中的尝试:

@Configuration
@ConfigurationProperties(prefix = "org-registry-list")
class OrgRegistryConfiguration {
  var organisations : List[Organisation] = List.empty
}

object OrgRegistryConfiguration {
  case class Organisation(orgId: Long, orgName: String)
}
  

返回List()


这适用于以下Java代码:

@Configuration
@ConfigurationProperties(prefix = "org-registry-list")
public class OrgRegistryConfiguration {

    private List<Organisation> organisations;

    public OrgRegistryConfiguration(List<Organisation> organisations) {
        this.organisations = organisations;
    }

    public OrgRegistryConfiguration() {
    }

    public List<Organisation> getOrganisations() {
        return organisations;
    }

    public void setOrganisations(List<Organisation> organisations) {
        this.organisations = organisations;
    }

    public static class Organisation {

        private long orgId;
        private String orgName;


        public Organisation(long orgId, String orgName) {
            this.orgId = orgId;
            this.orgName = orgName;
        }

        public Organisation() {}

        public long getOrgId() {
            return orgId;
        }
        public void setOrgId(long orgId) {
            this.orgId = orgId;
        }

        public String getOrgName() {
            return orgName;
        }
        public void setOrgName(String orgName) {
            this.orgName = orgName;
        }

    }

}
  

返回两个组织的列表

1 个答案:

答案 0 :(得分:0)

我设法解决了这个问题。这是我所做的:

  1. List更改为Array
  2. 将类重写为具有字段而不是构造函数参数
  3. 介绍scala.beans.BeanProperty

工作代码:

import scala.beans.BeanProperty

@Configuration
@ConfigurationProperties(prefix = "org-registry-list")
class OrgRegistryConfig() {
  @BeanProperty
  var organisations: Array[Organisation] = _
}

object OrgRegistryConfig {
  class Organisation() {
    @BeanProperty
    var orgId: Long = _
    @BeanProperty
    var orgName: String = _
  }
}