Java16引入了Records,这有助于在编写携带不可变数据的类时减少样板代码。当我尝试使用记录作为@ConfigurationProperties bean时,如下所示,我得到以下错误消息:
@ConfigurationProperties("demo")
public record MyConfigurationProperties(
String myProperty
) {
}***************************
APPLICATION FAILED TO START
***************************
Description:
Parameter 0 of constructor in com.example.demo.MyConfigurationProperties required a bean of type 'java.lang.String' that could not be found.如何将记录用作@ConfigurationProperties
发布于 2021-03-19 02:14:57
回答我自己的问题。
由于缺少无参数构造函数,Spring Boot无法构造bean,从而导致上述错误。记录隐式声明一个构造函数,每个成员都有一个参数。
Spring Boot允许我们使用@ConstructorBinding注释通过构造函数而不是setter方法来启用属性绑定(如the docs和对this question的回答中所述)。这也适用于记录,所以这是有效的:
@ConfigurationProperties("demo")
@ConstructorBinding
public record MyConfigurationProperties(
String myProperty
) {
}更新:从Spring Boot2.6开始,使用记录可以开箱即用,当记录只有一个构造函数时,不再需要@ConstructorBinding。请参阅release notes。
发布于 2021-07-13 15:26:42
如果您需要以编程方式声明默认值:
@ConfigurationProperties("demo")
public record MyConfigurationProperties(String myProperty) {
@ConstructorBinding
public MyConfigurationProperties(String myProperty) {
this.myProperty = Optional.ofNullable(myProperty).orElse("default");
}
}java.util.Optional属性:
@ConfigurationProperties("demo")
public record MyConfigurationProperties(Optional<String> myProperty) {
@ConstructorBinding
public MyConfigurationProperties(String myProperty) {
this(Optional.ofNullable(myProperty));
}
}@Validated和java.util.Optional的组合:
@Validated
@ConfigurationProperties("demo")
public record MyConfigurationProperties(@NotBlank String myRequiredProperty,
Optional<String> myProperty) {
@ConstructorBinding
public MyConfigurationProperties(String myRequiredProperty,
String myProperty) {
this(myRequiredProperty, Optional.ofNullable(myProperty));
}
}https://stackoverflow.com/questions/66696828
复制相似问题