如何使用Kotlin数据类配置多个前缀ConfigurationProperties

时间:2020-04-11 13:00:19

标签: spring spring-boot kotlin

库A中的kotlin数据类,用于配置不可变属性(所有属性均设置为val而非var):

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

从Spring Boot 2.2.0开始,可以使用以下代码配置单个但固定的前缀:

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

我的应用程序依赖于库A,但需要使用不同的前缀(例如Cfgapp.cfg1)配置多个app.cfg2实例。这些前缀由应用程序选择。怎么样?

1 个答案:

答案 0 :(得分:0)

您可以使用示例中的类声明多个相同类型的bean,并根据需要为其定义前缀。

@Configuration
class CfgConfiguration {

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

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

您可以根据需要添加任意数量,绑定属性将可用。