Spring Boot ConfigurationProperties validate

Posted 沧海一滴

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了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的主要内容,如果未能解决你的问题,请参考以下文章

为啥 Spring Boot Application 类需要有 @Configuration 注解?

Using Spring Boot —— Configuration Classes

spring-boot-configuration-processor的作用

从 Spring Boot 应用程序中排除 @Configuration

在spring boot中根据属性加载@configuration

Spring Boot学习笔记总结