首页 > 解决方案 > 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用于验证。

如果可能,请附上链接作为参考

标签: javaspringspring-bootvalidationjavax.validation

解决方案


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");
    }

推荐阅读