可以说我为NewUserRequestBean
创建了一个名为@CheckUsernameAvailable
的验证器。
验证器将执行类似
的简单操作public boolean isValid(NewUserRequestBean request, ConstraintValidationContext context) {
String userName = request.getUserName();
User existingUser = userProviderService.getUser(userName);
if (existingUser != null) {
return false;
}
}
有没有一种方法可以重用existingUser
对象,从而做类似的事情
// if (existingUser != null)
else if (existingUser.getEmailAddress() == request.getUserEmailAddress()) {
sendObjectToCaller(existingUser);
// or returnObjectToCaller(existingUser);
}
答案 0 :(得分:0)
如果您使用的是Hibernate Validator,则可以查看动态有效负载。您的验证器实现如下所示:
@Override
public boolean isValid(NewUserRequestBean value, ConstraintValidatorContext context) {
// all the code you need
// make sure that you are working with Hibernate Validator contexts before unwrapping
if ( context instanceof HibernateConstraintValidatorContext ) {
context.unwrap( HibernateConstraintValidatorContext.class )
.withDynamicPayload( existingUser );
}
return validationResult;
}
,那么如果引发约束,您应该能够从约束违规中访问相同的有效负载:
Set<ConstraintViolation<NewUserRequestBean>> violations = // results of validation of your NewUserRequestBean...
// just get the violation and unwrap it to HibernateConstraintViolation.
// to stay on the safe side you should apply an instanceof check here as well before unwrapping
HibernateConstraintViolation<NewUserRequestBean> violation = violations.iterator().next()
.unwrap( HibernateConstraintViolation.class );
User existingUser = violation.getDynamicPayload( User.class );
有关更多信息,您可以检查这些动态有效载荷方法的javadocs,也请查看dynamic payloads文档中的本节