24.7.4. @ConfigurationProperties校验

Spring Boot会尝试校验@ConfigurationProperties类,只要它们标注了Spring的@Validated。你可以在你的配置类中直接使用JSR-303 javax.validation约束标注。确保在你的类路径中存在适用的JSR-303实现,再添加约束标注在你的域中:

@ConfigurationProperties(prefix="acme")
@Validated
public class AcmeProperties {

    @NotNull
    private InetAddress remoteAddress;

    // ... getters and setters

}

你也可以通过标注@Bean方法触发验证,用@Validated创建配置属性。

尽管在绑定后,内嵌属性也会被验证,但还是把相关的域标注上@Valid不失为一种良好的实践。这确保了即使没有找到内嵌属性,验证还是会被触发。下面的例子建立在之前的AcmeProperties示例之上: 为了校验内嵌属性的值,你需要使用@Valid注解关联的字段以触发它的校验,例如,建立在上面的FooProperties示例之上:

@ConfigurationProperties(prefix="acme")
@Validated
public class AcmeProperties {

    @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

    }

}

最后更新于

这有帮助吗?