执行特定的Javax验证组

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

班级:

@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());
    }
iCMS 回答:执行特定的Javax验证组

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

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;

....
本文链接:https://www.f2er.com/1786207.html

大家都在问