Search code examples
spring-bootspring-cloud-config

How to map configuration objects to java object


I have a spring boot application which is using a spring cloud config. How can i map a configuration element with some java object.

My config is something like this:

clients:
- id         : 1
  name: client 1
  groups    : [a,b]

- id         : 2
  name: client 2
  groups    : [a]

And my java object is:

public class ClientInfo {
  private String clientId;
  private List<String> profiles;

  public ClientInfo(String clientId, List<String> pips) {
    this.clientId = clientId;
    this.profiles = pips;
  }
  public String getClientId() {
    return clientId;
  }

  public void setClientId(String clientId) {
    this.clientId = clientId;
  }

  public List<String> getProfiles() {
    return profiles;
  }

  public void setProfiles(List<String> profiles) {
    this.profiles = profiles;
  }
}

I want to map my configuration with List


Solution

  • Use below code to configure configuration properties in to java Object,

    @Component
    @EnableConfigurationProperties
    @ConfigurationProperties(prefix = "clients")
    public class ClientInfo {
    
    private String id;
    private String name;
    private List<String> groups;
    
    public String getId(){ return id;}
    
    public String getName(){ return name;}
    
    public List<String> getGroups(){ return groups;}
    
    }
    

    Check following for example http://docs.spring.io/spring-boot/docs/current/reference/html/boot-features-external-config.html

    Inject this class in another class :

    @Autowired
    private ClientInfo clientInfo;
    

    The above auto wiring will not work if the class is instantiated using "new operator".