1

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. Also whenever I auto generate constructor in IDEA IDE, annotations also auto attached in constructor parameters.

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.

If possible please also attach link as reference

MD Ruhul Amin
  • 4,386
  • 1
  • 22
  • 37

1 Answers1

1

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");
    }
fctmolina
  • 196
  • 2
  • 10
  • Thanks for your answer. can you give me a reference link? So that I can use that as evidence! – MD Ruhul Amin Jul 24 '19 at 08:34
  • https://www.baeldung.com/spring-boot-bean-validation I've already tried using validations and custom validations in Spring Boot. Note: The exception thrown is ConstraintValidationException – fctmolina Jul 24 '19 at 08:38