24.7.4 @ConfigurationProperties Validation

Spring Boot会尝试去校验被@ConfigurationProperties注解的类(经过笔者的测试,无论这些类加了@Validated注解与否,Spring Boot都会去校验)你只需要将JSR-303 javax.validation约束注解添加到@ConfigurationProperties类上即可,只是要确保你的classpath里面有JSR-303的实现,比如最常用的是(org.hibernate:hibernate-validator,这个依赖既带有javax.validation的api又带有实现):

官方文档建议你这样写:

@ConfigurationProperties(prefix="foo")
@Validated
public class FooProperties {

    @NotNull
    private InetAddress remoteAddress;

    // ... getters and setters

}

经过笔者测试,如下写法也行

@ConfigurationProperties(prefix="foo")
public class FooProperties {

    @NotNull
    private InetAddress remoteAddress;

    // ... getters and setters

}

@ConfigurationProperties("foo")
@Bean
public FooProperties fooProperties() {
    return new FooProperties();
}

public class FooProperties {
    @NotNull
    private InetAddress remoteAddress;

    // ... getters and setters

}

如果要校验嵌套类,则必须使用@Valid注解关联的字段以触发它的校验,例如:

@ConfigurationProperties(prefix="connection")
@Validated
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

    }

}

默认地,Spring会提供一个ValidatorLocalValidatorFactoryBean)来处理所有的JSR-303约束注解(包括你自己新增加的),你也可以定制一个个性化的Spring Validator(a custom Spring Validator)来替代原先的,只要创建一个叫做configurationPropertiesValidator(bean的id,如果使用@Bean方法来创建的话,方法名必须是configurationPropertiesValidator,因为默认使用方法名作为bean的id)的bean。@Bean方法需要声明为static,因为配置属性校验器在应用程序生命周期中创建的比较早,将@Bean方法声明为static允许该bean在创建时不需要实例化@Configuration类,从而避免了早期实例化(early instantiation)的所有问题。相关的示例可以看property validation sample

spring-boot-actuator(用来监控关联的spring boot项目的)模块包含一个暴露所有@ConfigurationProperties beans的端点(endpoint),通过浏览器打开/configprops进行浏览,或使用等效的JMX端点,具体参考Production ready features,可以看到spring-boot-actuator模块所有的端点以及各自的用途。

results matching ""

    No results matching ""