2

Background:

I have read a lof of examples on how to use ConfigurationPropertiesto read a list from config.. see below

  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

.. and more.


I am not able to implement this in Scala. I want to get a list of organisations (id and name) from application.yml, but it always returns an empty list.

application.yml

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

This is my attempt in Scala:

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

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

Returns List().


This works with the following Java code:

@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;
        }

    }

}

Returns list of two organisations

Mr.Turtle
  • 2,950
  • 6
  • 28
  • 46

1 Answers1

0

I managed to solve this. Here is what I did:

  1. Changed List to Array
  2. Rewrite the class to have fields instead of constructor parameters
  3. Introduce scala.beans.BeanProperty

Working code:

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 = _
  }
}
Mr.Turtle
  • 2,950
  • 6
  • 28
  • 46