【问题标题】:jsr303 validate 2 properties with only one custom validatorjsr 303 仅使用一个自定义验证器验证了 2 个属性
【发布时间】:2012-10-17 14:23:27
【问题描述】:

我的验证有问题。是否可以仅使用一个 ConstraintValidator 来验证 bean 的两个属性?我有类似以下内容:

@Component
public class CheckSomeBeanPropertiesValidator implements ConstraintValidator<CheckSomeBeanProperties, SearchFormBean> {

@Autowired
SomeApplicationService applicationService;

public void initialize(CheckSomeBeanProperties checkSomeBeanProperties) {
}

public boolean isValid(SearchFormBean searchFormBean, ConstraintValidatorContext context) {

ReturnSearchBean searchBean = applicationService.findBySearchBean(searchFormBean);

if(searchBean.isNoResults()) return false; // it will return the message No data found

if(searchBean.isTooManyDataReturned()) return false; // it will return too many records found

return true;
}
}

在 CheckSomeBeanPropertiesValidator 中,我调用了 SomeApplicationService 服务,该服务返回一些搜索到的数据,调用 findBySearchBean。除了调用多个自定义的 ConstraintValidator(和多个 findBySearchBean)之外,是否可以只调用一次服务并检查两个不同的属性?

谢谢

再见

【问题讨论】:

  • 您的问题很模糊,您还应该发布有关如何使用自定义约束的代码。我只是猜测您在两个不同的属性上使用此自定义约束,但您只想拥有一次。这只有在您使用类级别约束时才有可能。再说一次,我只是在猜测:-)
  • 嗨,我在类级别上使用它,例如:@CheckSomeBeanPropertiesValidator public class SearchFormBean implements Serializable{ boolean noResults; boolean tooManyDataReturned; ....} 但问题是我想根据 bean 的哪个布尔值是真的返回两条不同的消息。我不想验证 2 个不同的属性调用两次相同的服务 findBySearchBean。谢谢你

标签: bean-validation


【解决方案1】:

如果您想根据验证结果更改错误消息,您应该使用 ConstraintValidatorContext。您可以禁用默认错误消息并构建自己的错误消息。比如:

 constraintContext.disableDefaultConstraintViolation();
 constraintContext.buildConstraintViolationWithTemplate( "{mykey}"  ).addConstraintViolation();

您还可以调整约束违规的属性路径。 ConstraintValidatorContext 提供了流畅的 API。只需检查 Javadocs 或使用您的 IDE 进行探索 :-)

【讨论】:

    猜你喜欢
    • 2012-06-18
    • 2015-07-31
    • 2023-03-29
    • 2015-03-28
    • 1970-01-01
    • 1970-01-01
    • 2011-08-09
    • 1970-01-01
    • 2018-08-24
    相关资源
    最近更新 更多