annotations - understanding Spring's Bean validation -


i'm hoping can me understand spring's bean validation. first, if have annotated class,

@entity public class user {     @notnull     @column(name = "username", unique = true, nullable = false)     private string username;      public string getusername()     {         return username;     }      public void setusername(string username)     {         this.username = username;     } } 

i can still construct object new user(); invalid. question is, when/where/how should validation occur? proper, or have done wrong? suppose should requiring not-null fields set in constructor, if that's method of enforcement, what's purpose of providing annotation?

you can create new user object though invalid @ time of creation, because validation not invoked. must invoke bean validation on given bean either manually or using spring facilities validation. instance consider usage in spring controllers:

@requestmapping(method=post) public void save(@requestbody @valid user user) { } 

in case spring invoke validation on post request handler method , return http 400 if validation fails. internally taken care of requestresponsebodymethodprocessor.

you invoke validation on given object manually so:

validatorfactory factory = validation.builddefaultvalidatorfactory(); validator validator = factory.getvalidator(); set<constraintviolation<user>> errors = validator.validate(user); 

and answer question, can enforce non null values set in constructor. let's consider first example controller instance. not use constructor, use default constructor create empty user object , map request values properties, method of enforcement not work here.

also, might want have object in invalid state before initialized , validate before expects object valid.


Comments