Reputation: 2924
Suppose I have a class, what is the order of validation in a SpringBoot class object. After an object gets created then the fields are populated or does the validation happens before the objects are populated, at the time of setting of the field values this validation happens. Or after the object is created then by a get call we validate the object field values.
package com.bablo.google.request;
import java.io.Serializable;
import java.util.Set;
import javax.validation.constraints.NotNull;
public class SomeRequest implements Serializable {
/**
*
*/
private static final long serialVersionUID = 1L;
@NotNull
private Long userId;
private String resNote; //this is not annotated with @NotNull
@NotNull
private String revTag;
public Long getUserId() {
return userId;
}
public void setUserId(final Long userId) {
this.userId = userId;
}
public String getResNote() {
return responseNote;
}
public void setResNote(final String resNote) {
this.resNote = resNote.trim(); //Call to trim() method of the String object.
}
public String getRevTag() {
return revTag;
}
public void setRevTag(final String revTag) {
this.revTag = revTag.trim(); //Call to the trim() method of the String object.
}
}
What is the way that validation will happen in a class? What is the mechanism of validating the fields, does the @NotNull validation or for that matter any validation depends on the getter methods to do the validation? Do they first call the setter methods to do the validation?
Upvotes: 0
Views: 2745
Reputation: 1670
Splitting your questions and adding answers.
What is the order of validation in a SpringBoot class object?
Validation happens as part of data binding process. Every request parameter/path variable will be validated as per the marked annotation and only when the validation passes, the value will be assigned to the class object.
What is the way that validation will happen in a class?
Validation process differs for each binding mechanism. If the method parameter is ModelAttribute/request parameter/path variable/Map etc. Spring uses different argument resolvers for each method parameter. If @Valid is added, then it enables validation during argument resolution process (Look out for RequestMappingHandlerAdapter where the whole magic is wired).
Does the @NotNull validation or for that matter any validation depends on the getter methods to do the validation? Do they first call the setter methods to do the validation?
Spring uses reflection to construct/validate the method argument class. Data binding and validation happens even without getters/setters.
Upvotes: 2
Reputation: 1369
You can validate manually by calling
@Autowired
private javax.validation.Validator validator;
...
validator.validate(new SomeRequest()); // you can also pass method's argument
or you can use auto validation
@Valid
+ @ExceptionHandler@Valid
+ BindingResult
Upvotes: 1