java - 'combining' 两个端点时 javax 验证注释重用的模式

标签 java validation javax.validation

我有一个 API,其中包含两个具有一对多关系的实体 FooBar,即每个 Bar 必须引用一个 Foo

我有端点来创建 FooBar - 这些端点具有使用 javax 验证定义的各自的 DTO。

public class CreateFooDto {
  @NotNull public Integer field1;
  @Length(min=1, max=8) public String field2;
}

public class CreateBarDto {
  @NotNull public Boolean field1;
  @NotEmpty public String field2;

  @NotNull public String fooId; // the foreign key to Foo
}

现在,我想要一个新端点,它创建一个 Bar Foo 在一起并将它们链接起来,而不是首先创建 Foo,然后创建传递 fooIdBar。我将需要所有相同的字段和相同的验证,但需要 CreateBarDto.fooId 除外。理想情况下,我想重用已经定义的 javax 验证,而不是重复它们。

我想将现有的 DTO 嵌套在新端点的组合 DTO 中,但是 CreateBarDto.fooId 上的 @NotNull 存在问题 - 事实上它是不需要。到目前为止,我想出的最佳解决方案是:

public class CreateBarWithFooDto {
  @Valid public CreateFooDto foo;
  @Valid public CreateBarDto bar;
}

public class CreateBarDto {
  @NotNull public Boolean field1;
  @NotEmpty public String field2;

  public String fooId; // the foreign key to Foo
  public boolean fooIdNotRequired; // optional flag to indicate fooId not required

  @AssertTrue
  public boolean isFooIdRequired() {
    return fooIdNotRequired || fooId != null;
  }
}

虽然这有效,但它确实很笨重。只是想知道是否有人可以建议一个更好的模式来重用这样的 javax 验证,或者是否有任何我不知道的 javax 注释可能会对此有所帮助?

最佳答案

一种选择是使用验证组。 javax.validation.groups 的 javadoc 说:

A group defines a subset of constraints. Instead of validating all constraints for a given object graph, only a subset is validated depending on the group targeted.

Each constraint declaration defines the list of groups it belongs to. If no group is explicitly declared, a constraint belongs to the Default group.

When applying validation, the list of target groups is passed along. If no group is explicitly passed along, the javax.validation.groups.Default group is used.

因此,在 CreateBarDto 中给您举个例子,我们可以有一个新组 MyFirstGrup.class,它仅为 field1 和 field2 的验证而定义

public class CreateBarDto {
  @NotNull(groups = {MyFirstGrup.class}) 
  public Boolean field1;
  @NotEmpty(groups = {MyFirstGrup.class})
  public String field2;

  @NotNull public String fooId; // the foreign key to Foo
}

您现在需要触发通常通过的特定组

validator.validate(yourBean, MyFirstGrup.class);

如果您使用 Spring,请检查 @Validated 注释,它支持指定您需要运行的组。更多信息here

关于java - 'combining' 两个端点时 javax 验证注释重用的模式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56021645/

相关文章:

Java 约束验证 - 未触发验证

java - 枚举继承,或类似的东西

javascript - 在 javascript 中使用鼠标滚轮事件验证输入字段的问题

java - 在 hibernate validator 中将参数从验证传递到自定义 validator

java - Spring 验证: Difference between validation annotations in Class Attributes VS Constructor Parameters

html - 所有 XTML 1.0 Strict 都与 HTML5 一样有效吗?

java - 在等待另一个变量初始化时,如何执行执行某些操作的方法?

Java 实例变量与局部变量

java - 使用 Java 的 POST 请求(AsyncTask)

javascript - 多个 IP 的正则表达式,以逗号分隔,带或不带子网