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校驗