问题
Suppose I have an @ConfigurationProperties
class which needs to validate a set of fields based on the value of another field. For example, SdkProperties
has an enabled
field. Only when enabled
is true
should the other fields be validated.
SdkProperties
@Configuration
@ConfigurationProperties(...)
@Data
@Validated
public class SdkProperties
{
private boolean enabled;
@NotEmpty
private String apiKey
// ... etc.
}
The @NotEmpty
annotation should only be validated if enabled
is true
.
What's the proper way to do this?
I have seen examples of using @AssertTrue
and an isValid
function to handle the validation by hand. But I don't want to do that.
I wonder if this is doable using validation groups?
回答1:
You could write a custom ConstraintValidator
.
@Configuration
@ConfigurationProperties(prefix = "sdk")
@Validated
@NotEmptyWhenEnabled // <----- custom validation -----
@Data
class SdkProperties {
private boolean enabled;
private String apiKey;
}
@Constraint(validatedBy = {NotEmptyWhenEnabledValidator.class})
@Target({ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
@interface NotEmptyWhenEnabled {
String message() default "SDK apiKey needed when SDK is enabled";
Class[] groups() default {};
Class<? extends Payload>[] payload() default {};
}
class NotEmptyWhenEnabledValidator implements ConstraintValidator<NotEmptyWhenEnabled,SdkProperties> {
@Override
public boolean isValid(SdkProperties sdkProperties,
ConstraintValidatorContext constraintValidatorContext) {
boolean enabled = sdkProperties.isEnabled();
boolean empty = null == sdkProperties.getApiKey() || sdkProperties.getApiKey().isEmpty();
return !enabled || (enabled && !empty);
}
}
Then you get a nice message on startup when SDK is enabled but the API-key is not provided.
***************************
APPLICATION FAILED TO START
***************************
Description:
Binding to target org.springframework.boot.context.properties.bind.BindException: Failed to bind properties under 'sdk' to so.demo.SdkProperties$$EnhancerBySpringCGLIB$$1ecd6003 failed:
Reason: SDK apiKey needed when SDK is enabled
Action:
Update your application's configuration
Process finished with exit code 0
EDIT
Since spring-boot-2.2.0.RELEASE
(16 Oct 2019) you have another option.
You could validate the properties in the constructor.
by using: Immutable @ConfigurationProperties binding
Configuration properties now support constructor-based binding, which allows a
@ConfigurationProperties
-annotated class to be immutable. Constructor-based binding can be enabled by annotating a@ConfigurationProperties
class or one of its constructors with@ConstructorBinding
. Annotations such as@DefaultValue
and@DateTimeFormat
can be used on constructor parameters that are provided by configuration property binding.
ref: boot-features-external-config-constructor-binding
so in your case...
@ConfigurationProperties(prefix = "sdk")
class SdkProperties {
private boolean enabled;
private String apiKey;
@ConstructorBinding
public SdkProperties(boolean enabled, String apiKey) {
this.enabled = enabled;
this.apiKey = apiKey;
// direct validation in the constructor
boolean apiKeyNullOrEmpty = null == apiKey || apiKey.isEmpty();
Assert.isTrue(!enabled || !apiKeyNullOrEmpty, "When SDK is enabled, a SDK-api key is mandatory!");
}
public boolean isEnabled() { return enabled; }
public void setEnabled(boolean enabled) { this.enabled = enabled; }
public String getApiKey() {return apiKey; }
public void setApiKey(String apiKey) { this.apiKey = apiKey; }
}
来源:https://stackoverflow.com/questions/58435628/validate-fields-only-if-other-field-is-false