@Required 即使在初始化 bean 时也会导致异常

@Required causes exceptions even when bean is initialized

如果我的任何 bean 在初始化期间未完全配置,我希望 Spring Boot 抛出异常。我认为这样做的正确方法是用 @Required 注释相关 bean 方法,但它的行为并不像我预期的那样。

application.yml:

my_field: 100

简单 bean class:

package com.example.demo;

import org.springframework.beans.factory.annotation.Required;
import org.springframework.stereotype.Component;

@Component
public class MyProperties {
    private int myField;

    public MyProperties(){}

    @Required
    public void setMyField(int myField) {
        this.myField = myField;
    }

    @Override
    public String toString() {
        return  "{myField=" + myField + '}';
    }
}

我的申请class:

package com.example.demo;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;

import javax.annotation.PostConstruct;

@SpringBootApplication
public class DemoApplication {

    @Bean
    @ConfigurationProperties
    public MyProperties getMyProperties() {
        return new MyProperties();
    }

    @PostConstruct
    public void init() {
        MyProperties myProperties = getMyProperties();
        System.out.println(myProperties);
    }

    public static void main(String[] args) {
        SpringApplication.run(DemoApplication.class, args);
    }
}

在 DemoApplication 的 init 方法中,我正在打印生成的 bean 对象。如果没有 @Required 注释,它会被正确加载并打印 {myField=100}。但是,当我添加注释时它抛出这个异常:

org.springframework.beans.factory.BeanInitializationException: Property 'myField' is required for bean 'myProperties'

尽管配置文件包含所需的值,但仍然如此。

告诉 Spring 字段为必填项的正确说法是什么?

来自docs

Spring Boot will attempt to validate @ConfigurationProperties classes whenever they are annotated with Spring’s @Validated annotation. You can use JSR-303 javax.validation constraint annotations directly on your configuration class. Simply ensure that a compliant JSR-303 implementation is on your classpath, then add constraint annotations to your fields

您应该声明myField如下:

@NonNull
private int myField;