简体   繁体   English

Spring 验证:Class Attributes VS Constructor Parameters 中验证注解的区别

[英]Spring validation: Difference between validation annotations in Class Attributes VS Constructor Parameters

I have the following Model Object:我有以下模型对象:

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

In this Message class each field is annotated with validation constrains.在这个Message类中,每个字段都用验证约束进行注释。 Also whenever I auto generate constructor in IDEA IDE, annotations also auto attached in constructor parameters.此外,每当我在IDEA IDE 中自动生成构造函数时,注释也会自动附加到构造函数参数中。

My question is: Is there any side effect if I remove these constrains either from constructor parameters or field/object property ?我的问题是:如果我从构造函数参数字段/对象属性中删除这些约束,是否有任何副作用

How internally those validation are working?这些验证在内部如何运作?

I'm using javax.validation.Validator::validate for validation.我正在使用javax.validation.Validator::validate进行验证。

If possible please also attach link as reference如果可能,请附上链接作为参考

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. Spring boot 会自动注入您的 Message 类,因此您只需将它传递到您的控制器中。 Sample usage in Controller/RestController: 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");
    }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM