Multiple validator @ConfigurationProperties beans in Spring environment

When using the @ConfigurationProperties annotation to add properties to a bean, Spring provides the ability to define a custom validator to validate these properties.

ConfigurationPropertiesBindingPostProcessor searches for this validator using the fixed bean "configurationPropertiesValidator" and class org.springframework.validation.Validator .

Now suppose I have @ConfigurationProperties with its validator in module A. Another module B has a dependency on module A. Module B also defines its own @ConfigurationProperties and its own validator.

When the application loads, the post processor takes only one of these beans. This disables the other part of the check.

Is there a solution? How can I keep both means of checking configuration properties enabled in my application?

+6
source share
1 answer

I just ran into the same problem and realized that ConfigurationPropertiesBindingPostProcessor checks if the class annotated with @ConfigurationProperties implements the Validator interface itself. (see org.springframework.boot.context.properties.ConfigurationPropertiesBindingPostProcessor#determineValidator )

So, the solution is to move the entire property check to the annotated property class:

 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" ); } } } 
+6
source

All Articles