multiple prefixes for @ConfigurationProperties

Viewed 3912

I have an application.properties file with the following content.

server.name
server.id
server.ipadd

and I am using the following annotation to read in configProperties.java

@ConfigurationProperties(prefix = "server")
private String name;
private String ipadd;

Now I have included extra properties.

server.client.type
server.client.location

and want to read these new properties. How can I read these in the same configProperties.java file? Looking for something like the following formats which includes multiple prefixes, I know these are invalid.

 @ConfigurationProperties(prefix = "server", prefix = "server.client")
or
@ConfigurationProperties(prefix = "server")
@ConfigurationProperties(prefix = "server.client")
3 Answers

You need to create a new class like

public class ClientProperties {
   private String type;
   private String location;
}

and in your configuration prefixed with server you add it

private String name;
private String ipadd;
private ClientProperties client;

Answering your question about

configProperties.getClientProperties().getLocation()

I had to deal with a similar thing, and you can just wrap that call in your ConfigProperties class that looks like this:

@ConfigurationProperties
public ConfigProperties{
    private String name;
    private String ipadd;
    private ClientProperties client;
    public static class ClientProperties {
       private String type;
       private String location;
    }
    public String getType(){return client.getType();}
}

So your internal structure is correct, but you can access the properties from the top-level class. In my case I was using generated git properties that I couldn't reformat and this was easier than re-generating the files.

Here is an example of what you are trying to do.

@Configuration
public class MultipleConfigPrefixExample {
  @Bean
  @ConfigurationProperties(prefix = "config.first.part")
  public FirstPart getFirstPart(){
    return new FirstPart();
  }

  @Bean
  @ConfigurationProperties(prefix = "info.another.part")
  public AnotherPart getAnotherPart(){
    return new AnotherPart();
  }

  @Getter
  @Setter
  public static class FirstPart {
    private String element1;
    private String element2;
  }


  @Getter
  @Setter
  public static class AnotherPart {
    private String element1;
    private String element2;
  }
}

Annotations @Getter @Setter are from lombok.

Related