首页 > 代码库 > Spring Boot ConfigurationProperties validate

Spring Boot ConfigurationProperties validate

 

 

24.7.4 @ConfigurationProperties Validation

Spring Boot will attempt to validate external configuration, by default using JSR-303 (if it is on the classpath).
You can simply add JSR-303 javax.validationconstraint annotations to your @ConfigurationProperties class:

@ConfigurationProperties(prefix="foo")public class FooProperties {    @NotNull    private InetAddress remoteAddress;    // ... getters and setters}

 

In order to validate values of nested properties, you must annotate the associated field as @Valid to trigger its validation. For example, building upon the aboveFooProperties example:

@ConfigurationProperties(prefix="connection")public class FooProperties {    @NotNull    private InetAddress remoteAddress;    @Valid    private final Security security = new Security();    // ... getters and setters    public static class Security {        @NotEmpty        public String username;        // ... getters and setters    }}

You can also add a custom Spring Validator by 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 be created without having to instantiate the @Configuration class. This avoids any problems that may be caused by early instantiation. There is a property validation sample so you can see how to set things up.

 

Spring Boot ConfigurationProperties validate