我們正在為控制器端點中使用的請求物件使用 spring 自定義驗證器。我們實作它的方式與下面鏈接中的實作方式相同:
https://www.baeldung.com/spring-mvc-custom-validator
我們面臨的問題是,如果特定欄位也依賴于其他輸入欄位,它就無法作業。例如,我們將以下代碼作為控制器端點的請求物件:
public class FundTransferRequest {
private String accountTo;
private String accountFrom;
private String amount;
@CustomValidator
private String reason;
private Metadata metadata;
}
public class Metadata {
private String channel; //e.g. mobile, web, etc.
}
基本上@CustomValidator 是我們的自定義驗證器類,我們想要的邏輯是,如果從元資料提供的通道是“WEB”。不需要請求的“原因”欄位。否則,它將是必需的。
有沒有辦法做到這一點?我做了額外的研究,看不到任何處理這種情況的方法。
uj5u.com熱心網友回復:
顯然,如果您需要訪問自定義驗證器中的多個欄位,則必須使用類級別的注釋。
你提到的同一篇文章有??一個例子:https ://www.baeldung.com/spring-mvc-custom-validator#custom-class-level-validation
在您的情況下,它可能看起來像這樣:
@Constraint(validatedBy = CustomValidator.class)
@Target({ ElementType.TYPE })
@Retention(RetentionPolicy.RUNTIME)
public @interface CustomValidation {
String message() default "Reason required";
String checkedField() default "metadata.channel";
String checkedValue() default "WEB";
String requiredField() default "reason";
Class<?>[] groups() default {};
Class<? extends Payload>[] payload() default {};
}
package com.example.demo;
import org.springframework.beans.BeanWrapperImpl;
import org.springframework.stereotype.Component;
import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;
/*
If the supplied channel from Metadata is "WEB". The field "reason" of the request won't be required.
Else, it will be required.
*/
@Component
public class CustomValidator implements ConstraintValidator<CustomValidation, Object> {
private String checkedField;
private String checkedValue;
private String requiredField;
@Override
public void initialize(CustomValidation constraintAnnotation) {
this.checkedField = constraintAnnotation.checkedField();
this.checkedValue = constraintAnnotation.checkedValue();
this.requiredField = constraintAnnotation.requiredField();
}
@Override
public boolean isValid(Object value, ConstraintValidatorContext context) {
Object checkedFieldValue = new BeanWrapperImpl(value)
.getPropertyValue(checkedField);
Object requiredFieldValue = new BeanWrapperImpl(value)
.getPropertyValue(requiredField);
return checkedFieldValue != null && checkedFieldValue.equals(checkedValue) || requiredFieldValue != null;
}
}
用法將是:
@CustomValidation
public class FundTransferRequest {
...
或指定引數:
@CustomValidation(checkedField = "metadata.channel",
checkedValue = "WEB",
requiredField = "reason",
message = "Reason required")
public class FundTransferRequest {
...
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/485908.html
