gpt4 book ai didi

Java jsr 303从带注释的字段访问bean字段

转载 作者:太空宇宙 更新时间:2023-11-04 07:35:32 25 4
gpt4 key购买 nike

在我的场景中,我尝试创建注释来验证一个字段是否已填充(如果另一个字段具有某种值)。

界面如下所示:

@Target({ElementType.FIELD, ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Constraint(validatedBy = RequiredIfFieldHasValueValidator.class)
public @interface RequiredIfFieldHasValue
{
String message() default "Required if selected";

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

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

/*
FieldName against which we validate
*/
String fieldName() default "";

/*
Field value that indicates requirement
*/
String fieldValue() default "";
}

和实现:

public class RequiredIfFieldHasValueValidator implements ConstraintValidator<RequiredIfFieldHasValue, String>
{
private String fieldName;
private String fieldValue;

@Override
public void initialize( RequiredIfFieldHasValue constraintAnnotation )
{
fieldName = constraintAnnotation.fieldName();
fieldValue = constraintAnnotation.fieldValue();
validateParameters();
}

@Override
public boolean isValid( String value, ConstraintValidatorContext context )
{
System.out.println( "Validate against fieldname: " + fieldName + " fieldvalue: " + fieldValue );
//
//Validation should be here (1)
//
return false;
}

private void validateParameters()
{
if ( "".equals( fieldName ) || fieldName == null )
{
throw new IllegalArgumentException( "The fieldname cannot be null" );
}
}
}

示例用法:

public class Form {
private String type;
@RequiredIfFieldHasValue(fieldName = "type", fieldValue = "DICT")
private String dictValue;
}

我在 Spring MVC 中使用它并根据请求进行验证,如下所示:

public String myFormPostPost( Model model, @Valid @ModelAttribute MyForm form, indingResult result )

所以我的目标是:如果字段类型的值等于 DICT,则字段 dictValue 应该是必需的(不为空)

我的问题是我是否可以访问Validation should be here (1)中的当前bean值?我知道我可以对整个 bean 进行注释,但我更喜欢这种方式。

最佳答案

嗯,我想这是不可能的,所以我坚持使用类注释的解决方案: Cross field validation with Hibernate Validator (JSR 303)

关于Java jsr 303从带注释的字段访问bean字段,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16934883/

25 4 0
文章推荐: c - 这是解决循环 typedef 依赖的正确方法吗?
文章推荐: css - 正确导入后, Material 样式未应用于 Angular 应用程序
文章推荐: C 字符串作为链表?
文章推荐: java - Struts