Spring 来自 属性 文件的不可变 Bean
Spring immutable Bean from property file
在 kotlin/spring 引导项目中,我可以使用此语法从 属性 文件创建一个 bean
@Component
@ConfigurationProperties(prefix = "my.awesome.prop")
data class MyAwesome(
var name: String = ""
)
我找不到使对象不可变的方法,所有属性都必须 var
。有没有更好的方法?
你试过吗?
@ConstructorBinding
@ConfigurationProperties(prefix = "my.awesome.prop")
data class MyAwesome(
val name: String
)
然后例如在您的配置中 class:
@Configuration
@EnableConfigurationProperties(MyAwesome::class)
class MyConfig(private val myAwesome: MyAwesome) {}
从 Spring Boot 2.2 开始,我们可以使用 @ConstructorBinding
注释来绑定我们的配置属性。
这实质上意味着@ConfigurationProperties-annotated classes 现在可能是 不可变的.
@ConstructorBinding
注释表明配置属性应该通过构造函数参数而不是调用 setter 来绑定
需要强调的是,要使用构造函数绑定,我们需要使用 @EnableConfigurationProperties
或 @ConfigurationPropertiesScan
显式启用我们的配置 class
如果你没有配置 class 你可以在主应用上面添加它 class:
@SpringBootApplication
@EnableConfigurationProperties(MyAwesome::class)
在 kotlin/spring 引导项目中,我可以使用此语法从 属性 文件创建一个 bean
@Component
@ConfigurationProperties(prefix = "my.awesome.prop")
data class MyAwesome(
var name: String = ""
)
我找不到使对象不可变的方法,所有属性都必须 var
。有没有更好的方法?
你试过吗?
@ConstructorBinding
@ConfigurationProperties(prefix = "my.awesome.prop")
data class MyAwesome(
val name: String
)
然后例如在您的配置中 class:
@Configuration
@EnableConfigurationProperties(MyAwesome::class)
class MyConfig(private val myAwesome: MyAwesome) {}
从 Spring Boot 2.2 开始,我们可以使用 @ConstructorBinding
注释来绑定我们的配置属性。
这实质上意味着@ConfigurationProperties-annotated classes 现在可能是 不可变的.
@ConstructorBinding
注释表明配置属性应该通过构造函数参数而不是调用 setter 来绑定
需要强调的是,要使用构造函数绑定,我们需要使用 @EnableConfigurationProperties
或 @ConfigurationPropertiesScan
如果你没有配置 class 你可以在主应用上面添加它 class:
@SpringBootApplication
@EnableConfigurationProperties(MyAwesome::class)