如果我的任何 bean 在初始化期间未完全配置,我希望 Spring Boot 抛出异常。我认为正确的方法是使用 @Required
注释相关 bean 方法,但它的行为并不符合我的预期。
application.yml:
my_field: 100
简单的bean类:
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 + '}';
}
}
我的应用程序类:
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;
关于java - 即使 bean 已初始化,@Required 也会导致异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45878732/