gpt4 book ai didi

java - 如何在自定义验证注释上插入 ConstraintValidator 消息

转载 作者:行者123 更新时间:2023-11-30 01:56:30 26 4
gpt4 key购买 nike

我已经阅读了一些关于如何使用 Hibernate 的 ConstrainValidator 的问答和指南(例如 Hibernate Documentation ),但没有一个明确提及如何在 a 的特定位置中插入值。创建您自己的自定义验证注释时出现验证错误消息。

例如,如果我有一条如下所示的验证错误消息:

foo.bar.error=This value '{myValue}' is wrong.

如果验证失败,我希望获得以下消息:

The value 'some wrong value' is wrong.

验证将像这样使用:

public class SomeClass {

@CustomAnnotation(message="{foo.bar.error}")
public MyObject myObject;

...

}

public class MyObject {
private String myValue;

...
}

最佳答案

我找到了一种无需太多模糊即可插入消息的方法。

首先像以前一样设置您的 ValidationMessages.properties (或存储验证消息的任何位置):

foo.bar.error=This value '{wrongValue}' is wrong.

像平常一样创建注释:

import javax.validation.Constraint;
import javax.validation.Payload;
import java.lang.annotation.Documented;
import java.lang.annotation.Retention;
import java.lang.annotation.Target;

import static java.lang.annotation.ElementType.FIELD;
import static java.lang.annotation.RetentionPolicy.RUNTIME;

@Documented
@Constraint(validatedBy = CustomValueValidator.class)
@Target(FIELD)
@Retention(RUNTIME)
public @interface CustomAnnotation {
String message() default "{foo.bar.error}";

Class<?>[] groups() default {};

Class<? extends Payload>[] payload() default {};
}

像这样实现约束 validator :

import org.hibernate.validator.internal.engine.constraintvalidation.ConstraintValidatorContextImpl;

import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;

public class CustomValueValidator
implements ConstraintValidator<CustomAnnotation, MyObject> {

@Override
public void initialize(final CustomAnnotation constraintAnnotation) {
// Extract any value you would need from the annotation
}

@Override
public boolean isValid(final MyObject myObject,
final ConstraintValidatorContext context) {
boolean valid;

// Add your validations over the 'myObject' object

if (!valid) {
((ConstraintValidatorContextImpl) context)
.addMessageParameter("wrongValue", myObject.getMyValue());
}

return valid;
}
}

现在剩下的就是使用注释:

public class SomeClass {

// I'm using the default message. You could override it as a parameter
@CustomAnnotation
public MyObject anotherObject;

...

}

关于java - 如何在自定义验证注释上插入 ConstraintValidator 消息,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54319303/

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