java - Spring验证:类属性VS构造函数参数中验证注解的区别
问题描述
我有以下模型对象:
@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 中自动生成构造函数时,注释也会自动附加到构造函数参数中。
我的问题是:如果我从构造函数参数或字段/对象属性中删除这些约束,会有任何副作用吗?
这些验证在内部如何运作?
我javax.validation.Validator::validate
用于验证。
如果可能,请附上链接作为参考
解决方案
There will be no side effects if you remove the constraints in the constructor. The constraints in the field variable will still work.
You don't even need to create a constructor. Spring boot automatically injects your Message class so you only need to pass it in your controller. Sample usage in 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");
}
推荐阅读
- c - 诅咒中的非空格字符
- python - 如何在 Python 中将两个字符串变成一个列表?
- sql - 编写查询以显示在 6 月份加入的唯一学生 ID。按升序对结果进行排序
- c# - 到达列表中数组的特定元素
- c++ - 为什么带有 vptr 的对象要长 12 个字节?
- python - PyGame 游戏在幕后工作,但图像不会移动
- dotnetnuke - DNN 角色栏,API/personaBar/localization/gettable?culture=en-US 上的错误 500
- css - 覆盖 bootstrap4 复选框颜色
- html - 无法将数据从 mongodb 发送到网页
- unity3d - 如何识别地形的某些部分?