Spring环境中的多个@ConfigurationProperties验证器bean



当使用@ConfigurationProperties注释将属性注入bean时,Spring提供了定义自定义验证器来验证这些属性的能力。

ConfigurationPropertiesBindingPostProcessor使用固定的bean名称"configurationPropertiesValidator"和类org.springframework.validation.Validator查找这个验证器。

现在假设我在模块a中有一个@ConfigurationProperties及其验证器。另一个模块B依赖于模块a。模块B还定义了自己的@ConfigurationProperties和验证器。

当应用程序加载时,后处理器只会拾取其中一个bean。这将禁用验证的其他部分。

有解决办法吗?如何在应用程序中同时启用两个配置属性验证器?

我刚刚遇到了同样的问题,并意识到ConfigurationPropertiesBindingPostProcessor验证用@ConfigurationProperties注释的类是否实现了Validator接口本身。(见org.springframework.boot.context.properties.ConfigurationPropertiesBindingPostProcessor#determineValidator

因此,解决方案是将所有属性验证转移到带注释的属性类:

import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;
import org.springframework.validation.Errors;
import org.springframework.validation.ValidationUtils;
import org.springframework.validation.Validator;
@ConfigurationProperties("test.properties")
@Component
public class TestProperties implements Validator {
    private String myProp;
    public String getMyProp()
    {
        return myProp;
    }
    public void setMyProp( String myProp )
    {
        this.myProp = myProp;
    }
    public boolean supports( Class<?> clazz )
    {
        return clazz == TestProperties.class;
    }
    public void validate( Object target, Errors errors )
    {
        ValidationUtils.rejectIfEmpty( errors, "myProp", "myProp.empty" );
        TestProperties properties = (TestProperties) target;
        if ( !"validThing".equals( properties.getMyProp() ) ) {
            errors.rejectValue( "myProp", "Not a valid thing" );
        } 
    }
}

最新更新