1
如果在初始化過程中沒有完全配置我的Bean,我希望Spring Boot引發異常。我認爲這樣做的正確方法是用@Required
註釋相關Bean方法,但它不像我預期的那樣工作。@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'
儘管配置文件包含所需值,
什麼是正確的告訴春,一個字段是必需的?