2

在我的应用程序中,我有一个端点,它获取此对象的 JSON,然后调用calculateSomething()以将数字作为 http 响应返回。我用 . 验证这些值javax.validation。现在我有没有一种可能的方法来指定如何Example验证类的对象,或者在这个特定的端点(我有多个端点)中验证该对象的哪些值?例如,在这种情况下,如果此端点被调用,则只有和one将被验证,因为这些是 所需的唯一值。twothreecalculateSomething()

班级:

@Entity
@PrimaryKeyJoinColumn(name = "five")
 public class Example extends Foo {
 
    @ValidOne
    @Column
    private Integer one;

    @ValidTwo
    @Column
    private Integer two;

    @ValidThree
    @Column
    private Integer three;

    @ValidFour
    @Column
    private Integer four;

    @ValidFive
    @Column
    private Integer five;

    @Override
    public Integer calculateSomething() throws IllegalArgumentException{
        (one + two) * three
    } 
}

端点:

@PostMapping ("/calculateSomeNumber")
    public ResponseEntity calculateSomeNumber(@Valid @RequestBody Example example){
        return ResponseEntity.ok(example.calculateSomething());
    }
4

1 回答 1

2

您可以声明可以表示为组名称的接口。然后在定义验证约束时将其应用于特定组。要仅使用特定的验证组进行验证,只需将其应用于相关的控制器方法

public interface ValidOne {
}

public interface ValidTwo {
}
  
public class SomeController {
    @PostMapping ("/calculateSomeNumber")
    public ResponseEntity calculateSomeNumber(@Validated({ValidOne.class}) @RequestBody Example example){
        return ResponseEntity.ok(example.calculateSomething());
    }
...

@Entity
@PrimaryKeyJoinColumn(name = "five")
 public class Example extends Foo {
 
    @Column
    @NotNull(groups = ValidOne.class)
    private Integer one;

    @Column
    @NotNull(groups = ValidTwo.class)
    private Integer two;

....
于 2020-08-07T15:36:06.193 回答