我有以下模型对象:
@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/