仅通过注释排除某些案例的验证

时间:2014-01-07 07:45:50

标签: java validation annotations

我在Order.java,Shipping.java等多个地方使用名为Amount.java的公共实体来表示订单金额,运费金额等。

@JsonIgnoreProperties(ignoreUnknown = true)
@JsonSerialize(include = JsonSerialize.Inclusion.NON_NULL)
@JsonPropertyOrder({ "currency_code", "value" })
public class Amount {

@JsonProperty("currency_code")
@Length(max = 3, message = "field.length.max")
@NotEmpty(message = "field.nonEmpty")
@CurrencyCode
private String currencyCode;

@JsonProperty("value")
@JsonSerialize(using = NumberSerializer.class, include = JsonSerialize.Inclusion.NON_NULL)
@NotNull(message = "field.nonNull")
@Digits(integer = 6, fraction = 2, message = "field.amount.format")
@DecimalMin(value = "0.01", message = "field.number.positive")
private BigDecimal value;
}

如果您发现对值字段有限制,只允许传递正数。虽然大多数场景都是这种情况,但我遇到了一个不同的情况,其中说MyNewEntity.java我正在重复使用Amount.java,而对于MyNewEntity.java,我也应该允许负值。

有没有一种简单的方法可以使用或者可以使用某种排除机制?

1 个答案:

答案 0 :(得分:1)

您可以使用验证组功能。这是关于nice article的内容,但简而言之,它可以是这样的:

interface Positive {
}

class Amount {
   ...
   @DecimalMin(value = "0.01", message = "field.number.positive", groups=Positive.class)
   private BigDecimal value;  
}

// when you want to validate that value is positive
Set<ConstraintViolation<Order>> violations = validator.validate(order, Positive.class);

// when you don't want to validate that value is positive
Set<ConstraintViolation<MyNewEntity>> violations = validator.validate(myNewEntity);