I have the following Test.java POJO class being populated from a property file using the @ConfigurationProperties
annotation. I have seen the usage of @Required
annotation to make it a mandatory.
Rather than defining annotations at the setter method level, are there any annotations or options within the @Value
annotation that I can use for defining conditions like Mandatory, NotNull, etc?
@Component
@ConfigurationProperties(prefix = "com.test")
public class Test {
private String name;
@Required
public void setName(String name) {
name = name;
}
public String getName(String name) {
name = name;
}
}
Is this the right and only way for making a particular attribute mandatory? What are the other such annotations I could use for such conditions or validations purpose?
You can use validation for the properties, just not in the way you envisaged. What you can do is use standard validation annotations (like
@NotNull
etc.) on the fields (or setters) themselves.For example
Check out this part of the documentation
What the documentation essentially says, is that you simply have to have a compatible JSR303 validator implementation on the classpath, and use the relevant annotations. Spring Boot will take care of the rest