gpt4 book ai didi

java - Bean 验证 : How can I manually create a ConstraintViolation?

转载 作者:搜寻专家 更新时间:2023-10-31 19:46:07 25 4
gpt4 key购买 nike

我有一个特定的场景,我只能在流程的稍后时间点手动检查违规情况。

我想做的是抛出一个 ConstraintViolationException,并为其提供一个“真实的”ConstraintViolation 对象(当我在堆栈中捕获异常时,我使用#{validatedValue}violation.getPropertyPath() 参数)。

如果框架不通过注解为我创建一个 ConstraintViolation(我使用 Hibernate Validator),我该如何创建?

代码示例:

List<String> columnsListForSorting = new ArrayList<String>(service.getColumnsList(domain));
Collections.sort(columnsListForSorting);

String firstFieldToSortBy = this.getTranslatedFieldName(domain.getClass().getCanonicalName(), sortingInfo.getSortedColumn());
if (!columnsListForSorting.contains(firstFieldToSortBy)){
throw new ConstraintViolationException(<what here?...>);
}

谢谢。

最佳答案

我不喜欢 Hibernate Validator 的另一个原因。它们使得以编程方式创建一个简单的违规行为变得真的很困难,而这本来应该是非常简单的。我确实有测试代码,我需要在其中创建违规以提供给我的模拟子系统。

无论如何,除了滚动您自己的违规约束实现 - 这是我为字段创建违规所做的事情:

private static final String MESSAGE_TEMPLATE = "{messageTemplate}";
private static final String MESSAGE = "message";

public static <T, A extends Annotation> ConstraintViolation<T> forField(
final T rootBean,
final Class<T> clazz,
final Class<A> annotationClazz,
final Object leafBean,
final String field,
final Object offendingValue) {

ConstraintViolation<T> violation = null;
try {
Field member = clazz.getDeclaredField(field);
A annotation = member.getAnnotation(annotationClazz);
ConstraintDescriptor<A> descriptor = new ConstraintDescriptorImpl<>(
new ConstraintHelper(),
member,
annotation,
ElementType.FIELD);
Path p = PathImpl.createPathFromString(field);
violation = ConstraintViolationImpl.forBeanValidation(
MESSAGE_TEMPLATE,
MESSAGE,
clazz,
rootBean,
leafBean,
offendingValue,
p,
descriptor,
ElementType.FIELD);
} catch (NoSuchFieldException ignore) {}
return violation;

}

HTH

关于java - Bean 验证 : How can I manually create a ConstraintViolation?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22938407/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com