24.7.4. @ConfigurationProperties校验

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

  1. @ConfigurationProperties(prefix="connection")
  2. public class ConnectionProperties {
  3. @NotNull
  4. private InetAddress remoteAddress;
  5. // ... getters and setters
  6. }

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

  1. @ConfigurationProperties(prefix="connection")
  2. public class ConnectionProperties {
  3. @NotNull
  4. @Valid
  5. private RemoteAddress remoteAddress;
  6. // ... getters and setters
  7. public static class RemoteAddress {
  8. @NotEmpty
  9. public String hostname;
  10. // ... getters and setters
  11. }
  12. }

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

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