24.7.4 @ConfigurationProperties Validation
Spring Boot'll attempt to validate external configuration by default using JSR-303 (if it's on the classpath).
You can simply add JSR-303 javax.validation
constraint annotations to your @ConfigurationProperties
class:
@ConfigurationProperties (prefix= "foo")publicclass fooproperties { @NotNull Private inetaddress remoteaddress; // . .. getters and Setters }
In order to validate values of nested properties, you must annotate the associated field as to @Valid
trigger its Validati On. For example, building upon the above FooProperties
example:
@ConfigurationProperties (prefix= "Connection") Public classfooproperties {@NotNullPrivateinetaddress remoteaddress; @ValidPrivate FinalSecurity Security =NewSecurity (); //. .. getters and Setters Public Static classSecurity {@NotEmpty PublicString username; //. .. getters and Setters }}
You can also add a custom Spring by Validator
creating a bean definition called configurationPropertiesValidator
. The @Bean
method should be declared static
. The configuration Properties validator is created very early in the application ' s lifecycle and declaring the @Bean
method As static allows the bean to being created without has to instantiate the @Configuration
class. This avoids any problems the May is caused by early instantiation. There is a property validation sample so you can see how to set things up.
Spring Boot Configurationproperties Validate