Spring Boot的特性: @ConfigurationProperties校验

[

24.7.4. @ConfigurationProperties校验

Spring Boot将尝试校验外部配置,默认使用JSR-303(如果在classpath路径中),你只需要将JSR-303 javax.validation约束注解添加到@ConfigurationProperties类上:

@ConfigurationProperties(prefix="connection")
publicclassConnectionProperties{

    @NotNullprivate InetAddress remoteAddress;

    // ... getters and setters

}

为了校验内嵌属性的值,你需要使用@Valid注解关联的字段以触发它的校验,例如:

@ConfigurationProperties(prefix="connection")
publicclassConnectionProperties{

    @NotNull@Validprivate RemoteAddress remoteAddress;

    // ... getters and setterspublicstaticclassRemoteAddress{

        @NotEmptypublic String hostname;

        // ... getters and setters

    }

}

你也可以通过创建一个叫做configurationPropertiesValidator的bean来添加自定义的Spring Validator。@Bean方法需要声明为static,因为配置属性校验器在应用程序生命周期中创建的比较早,将@Bean方法声明为static允许该bean在创建时不需要实例化@Configuration类,从而避免了早期实例化(early instantiation)的所有问题。

注spring-boot-actuator模块包含一个暴露所有@ConfigurationProperties beans的端点(endpoint),通过浏览器打开/configprops进行浏览,或使用等效的JMX端点。

本文来自:Spring Boot的特性: @ConfigurationProperties校验
]
转载请保留页面地址:https://www.breakyizhan.com/springboot/3292.html

posted on 2020-07-06 21:48  MrAit  阅读(1046)  评论(0编辑  收藏  举报

导航