gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 05:32:59 24 4
gpt4 key购买 nike

我有以下模型对象:

@Validated
public class Message implements Serializable {
private static final long serialVersionUID = 9028633143475868839L;
@NonNull
@Size(min = 6, max = 6)
@Pattern(regexp = "[\\d]{6}")
private String id;
@NotNull
@Size(min = 1, max = 200)
private String title;
@NotNull
@Size(min = 1, max = 1000)
private String message;
@NotEmpty
private String type;
private String publishId;

public Message(){
}

public Message(@NonNull @Size(min = 6, max = 6) @Pattern(regexp = "[\\d]{6}") String id, @NotNull @Size(min = 1, max = 200) String title, @NotNull @Size(min = 1, max = 1000) String message, @NotEmpty String type, String publishId) {
this.id = id;
this.title = title;
this.message = message;
this.type = type;
this.publishId = publishId;
}
}

在此 Message 类中,每个字段都用验证约束进行注释。此外,每当我在 IDEA IDE 中自动生成构造函数时,注释也会自动附加到构造函数参数中。

我的问题是:如果我从构造函数参数字段/对象属性中删除这些约束,是否会产生任何副作用?? p>

这些验证在内部如何运作?

我使用 javax.validation.Validator::validate 进行验证。

如果可能,请附上链接作为引用

最佳答案

如果删除构造函数中的约束,不会有任何副作用。字段变量中的约束仍然有效。

您甚至不需要创建构造函数。 Spring boot 会自动注入(inject)您的 Message 类,因此您只需将其传递到 Controller 中即可。 Controller/RestController 中的示例用法:

ResponseEntity<String> addMessage(@Valid @RequestBody Message message) {
// If message is not valid. This will throw an exception which you can catch in the GlobalExceptionHandler.
return ResponseEntity.ok("Message is valid");
}

关于java - Spring 验证: Difference between validation annotations in Class Attributes VS Constructor Parameters,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57178329/

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