我有一个模型对象,它的验证需要一些更复杂的逻辑,包括对服务组件的调用。我试着这样实现:
public class RequestModuleEntryValidator implements Validator {
/*
* A service
*/
private final MyService myService;
/*
* Constructor for the module request validator
*/
@Autowired
public RequestModuleEntryValidator(MyService myService) {
this.myService= myService;
}
/*
* Checks if the validator supports the given class
*/
@Override
public boolean supports(Class<?> aClass) {
return RequestModuleEntry.class.equals(aClass);
}
/*
* Validates the given module request
* @param o The module request entry object
* @param errors The errors object
* @return Nothing
*/
@Override
public void validate(Object o, Errors errors) {
// Call to my service...
}
但我有一个警告:
在无效的Spring Bean 中定义的自动连接成员
所以我的问题是,当这个验证必须调用一些服务方法来决定模型数据是否有效时,我如何实现与@Valid
注释相对应的自定义验证。。。
为了创建自定义验证器,您可以实现ConstraintValidator接口。
为此,您需要创建一个自定义注释,并使用该注释注释模型类。
然后创建验证器类RequestModuleEntryValidator,该类包含ConstraintValidator接口并覆盖isValidat((方法,如下所示:
您的控制器方法可能如下所示:
public ResponseEntity<AnyObject> controllerMethod(@Valid @RequestBody PojoObject) {
.....
}
您的模型对象将看起来像:
@ValidPojoRequest // Custom Annotation
public class PojoObject {
....with all properties
}
自定义注释类将看起来像:
@Target({TYPE})
@Retention(RUNTIME)
@Constraint(validatedBy = PojoValidator.class)
public @interface ValidCancelRequest {
Class<?>[] groups() default {};
String message() default "{com.pojodetailvalidation.message}";
Class<? extends Payload>[] payload() default {};
}
然后您的PojoValidator.java文件将如下所示:
public class PojoValidator implements ConstraintValidator<ValidPojoRequest,PojoObject> {
@AutoWired
private MyService service;
public boolean isValid(PojoObject request, ConstraintValidatorContext context) {
// Call to your Service and check whether all conditions satisfy and accordingly return a boolean value.
//You can also return a proper error message for a particular property in your Pojo class by adding below
context.buildConstraintViolationWithTemplate("any message you wan to show to the one consuming your api").addConstraintViolation();
context.disableDefaultConstraintViolation();
return false;
}
}
isValid((方法返回布尔值。如果返回false,则验证失败