I would like for Spring Boot to throw an exception if any of my beans are not fully configured during initialization. I thought that the correct way to do that would be to annotate the relevance bean methods with @Required
, but it does not behave as I expect.
application.yml:
my_field: 100
Simple 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 + '}';
}
}
My application 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);
}
}
In the init method of DemoApplication I am printing the resulting bean object. Without the @Required
annotation it is loaded correctly and prints {myField=100}
. However, when I add the annotation it throws this exception:
org.springframework.beans.factory.BeanInitializationException: Property 'myField' is required for bean 'myProperties'
This is despite the fact that the config file contains the required value.
What is the correct to tell Spring that a field is required?
From the 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
You should declare myField
as follows:
@NonNull
private int myField;