简体   繁体   English

Java bean验证

[英]Java bean validation

I know this question has been asked before but unfortunately I can't get the answers to work ( How to validate field level constraint before class level constraint? ). 我知道之前曾有人问过这个问题,但是不幸的是我无法获得答案( 如何在类级别约束之前验证字段级别约束? )。

I have the following Pojo: 我有以下Pojo:

@ValidBalanceData(allowableBalanceDifference = 0.01)
public class Mutation {

    @NotNull() private BigDecimal balanceBefore;

    @NotNull() private BigDecimal balanceAfter;

    @NotNull() private BigDecimal amount;

    ....
}

I have implemented the ValidBalanceData annotation: 我已经实现了ValidBalanceData批注:

@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
@Constraint(validatedBy = BalanceDataConstraintChecker.class)
public @interface ValidBalanceData {
    String message() default "{nl.smith.balanceData.message}";

    double allowableBalanceDifference();

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

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

I also implemented the validatedBy class. 我还实现了validatedBy类。 Unfortunately the ValidBalanceData constraint is validated before the NotNull constraints. 不幸的是,ValidBalanceData约束先于NotNull约束进行验证。 Since the ValidBalanceData constraint assumes the balanceBefore, balanceAfter and amount values not to be null this results in a Nullpointer Exception. 由于ValidBalanceData约束假定balanceBefore,balanceAfter和amount值不为null,因此将导致Nullpointer异常。 How do I solve this problem? 我该如何解决这个问题? Can somebody give me a working example (using @GroupSequence and fields)? 有人可以给我一个有效的示例(使用@GroupSequence和字段)吗?

I found the answer: 我找到了答案:

@GroupSequence({ FieldChecks.class, Mutation.class })
@ValidBalanceData(allowableBalanceDifference = 0.01, groups =  Default.class)
public class Mutation {

private Integer id;

@NotNull(groups = FieldChecks.class)
private BigDecimal balanceBefore;

@NotNull(groups = FieldChecks.class)
private BigDecimal balanceAfter;

@NotNull(groups = FieldChecks.class)
private BigDecimal amount;

....

} }

FieldChecks is a userdefined empty marker interface and javax.validation.groups.Default comes from the validation jar. FieldChecks是一个用户定义的空标记接口,而javax.validation.groups.Default来自验证jar。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM