🔥码云GVP开源项目 12k star Uniapp+ElementUI 功能强大 支持多语言、二开方便! 广告
# 24.7.4. @ConfigurationProperties校验 Spring Boot将尝试校验外部配置,默认使用JSR-303(如果在classpath路径中),你只需要将JSR-303 `javax.validation`约束注解添加到`@ConfigurationProperties`类上: ```java @ConfigurationProperties(prefix="connection") public class ConnectionProperties { @NotNull private InetAddress remoteAddress; // ... getters and setters } ``` 为了校验内嵌属性的值,你需要使用`@Valid`注解关联的字段以触发它的校验,例如: ```java @ConfigurationProperties(prefix="connection") public class ConnectionProperties { @NotNull @Valid private RemoteAddress remoteAddress; // ... getters and setters public static class RemoteAddress { @NotEmpty public String hostname; // ... getters and setters } } ``` 你也可以通过创建一个叫做`configurationPropertiesValidator`的bean来添加自定义的Spring `Validator`。`@Bean`方法需要声明为`static`,因为配置属性校验器在应用程序生命周期中创建的比较早,将`@Bean`方法声明为`static`允许该bean在创建时不需要实例化`@Configuration`类,从而避免了早期实例化(early instantiation)的所有问题。相关的示例可以看[这里](https://github.com/spring-projects/spring-boot/tree/v1.4.1.RELEASE/spring-boot-samples/spring-boot-sample-property-validation)。 **注** `spring-boot-actuator`模块包含一个暴露所有`@ConfigurationProperties` beans的端点(endpoint),通过浏览器打开`/configprops`进行浏览,或使用等效的JMX端点,具体参考[Production ready features](https://github.com/cwiki-us-spring-guides/Spring-Boot-Reference-Guide/tree/0047aa8098a650dde0c93f4d2e91754c83468c4b/V.%20Spring%20Boot%20Actuator/40.%20Endpoints.md)。