gpt4 book ai didi

java - 执行特定组的 javax 验证

转载 作者:行者123 更新时间:2023-12-04 09:13:59 24 4
gpt4 key购买 nike

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

@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());
}

最佳答案

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

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;

....

关于java - 执行特定组的 javax 验证,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63304243/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com