【问题标题】:Spring does not complain if a property is not set when using ConfigurationProperties如果在使用 ConfigurationProperties 时未设置属性,Spring 不会抱怨
【发布时间】:2020-03-25 16:11:00
【问题描述】:

我有一个通过 ConfigurationProperties 配置的 bean:

@Component
@ConfigurationProperties(prefix = "mybean")
public class MyBean {

    @NotEmpty
    private String name;

    // Getters, setters, ...
}

我通过application.yml 配置字段值,但在“两个级别”中。在默认的 application.yml 中,我只是将值 设置为另一个属性的值

myBean.name: ${theValueOf.myBean.name}

在我的配置文件特定 YML 文件中:

theValueOf.myBean.name: 'The desired value'

我的期望是,如果我忘记指定属性theValueOf.myBean.name,那么应用程序在启动时应该会失败,并显示无法解析占位符“theValueOf.myBean.name”的消息。相反,字段name 被分配了值(字面意思)${theValueOf.myBean.name}

如果我用@Value("${myBean.name}") 注释name 字段(并且不使用ConfigurationProperties),并且忘记定义属性theValueOf.myBean.name,那么应用程序在启动时会失败——正如预期的那样。

我的问题是:当使用 ConfigurationProperties 时,如何使 Spring 在启动时失败并显示消息“无法解析占位符 ...”?

【问题讨论】:

    标签: spring spring-boot configuration configurationproperties proper


    【解决方案1】:

    只需在 @ConfigurationProperties 中使用 JSR303 注释标记您的属性。

    @Component
    @ConfigurationProperties(prefix = "mybean")
    public class MyBean {
    
       @NotEmpty
       private String name;
    }
    

    【讨论】:

    • 错误...你是对的!我忘了提到我已经用@NotEmpty 注释了该字段。但是,正如我所说,该字段被分配了非空值“${...}”,因此没有投诉。我更新了原始问题中的代码示例。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-10-30
    • 1970-01-01
    • 1970-01-01
    • 2016-08-20
    • 1970-01-01
    相关资源
    最近更新 更多