How to config a multiple prefix ConfigurationProperties with kotlin data class

Viewed 718

A kotlin data class in a library A for config immutable properties (all property set to val not var):

data class Cfg(
  val name: String, 
  ...
)

Since spring boot 2.2.0, can use the bellow code to config a single but fixed prefix:

@ConstructorBinding
@ConfigurationProperties(prefix = "app.cfg")
data class Cfg(...)

My app depends on the library A, but need to config multiple Cfg instance with different prefix, such as app.cfg1 and app.cfg2. And these prefixes is chosen by the app. How?

1 Answers

You can declare multiple beans of the same type and define prefixes for it as you need, using the class from your example it would be:

@Configuration
class CfgConfiguration {

  @Bean
  @ConfigurationProperties("app.cfg1")
  public Cfg cfg1() {
    return new Cfg();
  }

  @Bean
  @ConfigurationProperties("app.cfg2")
  public Cfg cfg2() {
    return new Cfg();
  }
}

You can add as much as you need and the binding properties will be available for you.

Related