首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何对记录使用@ConfigurationProperties?

如何对记录使用@ConfigurationProperties?
EN

Stack Overflow用户
提问于 2021-03-19 02:14:57
回答 2查看 1.1K关注 0票数 7

Java16引入了Records,这有助于在编写携带不可变数据的类时减少样板代码。当我尝试使用记录作为@ConfigurationProperties bean时,如下所示,我得到以下错误消息:

代码语言:javascript
复制
@ConfigurationProperties("demo")
public record MyConfigurationProperties(
        String myProperty
) {
}
代码语言:javascript
复制
***************************
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

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2021-03-19 02:14:57

回答我自己的问题。

由于缺少无参数构造函数,Spring Boot无法构造bean,从而导致上述错误。记录隐式声明一个构造函数,每个成员都有一个参数。

Spring Boot允许我们使用@ConstructorBinding注释通过构造函数而不是setter方法来启用属性绑定(如the docs和对this question的回答中所述)。这也适用于记录,所以这是有效的:

代码语言:javascript
复制
@ConfigurationProperties("demo")
@ConstructorBinding
public record MyConfigurationProperties(
        String myProperty
) {
}

更新:从Spring Boot2.6开始,使用记录可以开箱即用,当记录只有一个构造函数时,不再需要@ConstructorBinding。请参阅release notes

票数 15
EN

Stack Overflow用户

发布于 2021-07-13 15:26:42

如果您需要以编程方式声明默认值:

代码语言:javascript
复制
@ConfigurationProperties("demo")
public record MyConfigurationProperties(String myProperty) { 
    
    @ConstructorBinding
    public MyConfigurationProperties(String myProperty) {
        this.myProperty = Optional.ofNullable(myProperty).orElse("default");
    }
}

java.util.Optional属性:

代码语言:javascript
复制
@ConfigurationProperties("demo")
public record MyConfigurationProperties(Optional<String> myProperty) {

    @ConstructorBinding
    public MyConfigurationProperties(String myProperty) {
        this(Optional.ofNullable(myProperty));
    }
}

@Validatedjava.util.Optional的组合:

代码语言:javascript
复制
@Validated
@ConfigurationProperties("demo")
public record MyConfigurationProperties(@NotBlank String myRequiredProperty,
                                        Optional<String> myProperty) {

    @ConstructorBinding
    public MyConfigurationProperties(String myRequiredProperty, 
                                     String myProperty) {
        this(myRequiredProperty, Optional.ofNullable(myProperty));
    }
}

基于此Spring Boot issue

票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/66696828

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档