spring - how to use Java validator annotations from constructor? -


i have value object holds string. string subject restrictions (length, allowed characters, etc).

i use java or spring validation api validating object. validate domain object @ creation time (in constructor).

sample code realises (validates this using validation api):

void validate() {         localvalidatorfactorybean localvalidatorfactorybean = new localvalidatorfactorybean();         set<constraintviolation<msisdn>> violations = localvalidatorfactorybean.getvalidator().validate(this);         if (!violations.isempty()) {             throw new constraintviolationexception(violations);         }     } 

i not know how instance of javax.validation.validator constructor.

in spring-managed code (service) @autowire instance of javax.validation.validator or org.springframework.validation.validator , works.

but how make work outside of spring-managed code (in constructor of value object, stands on own)?

i know can write validation rules using ifs, validation annotations makes code simpler.

hibernate validator documentation describes how instance of javax.validation.validator

validatorfactory factory = validation.builddefaultvalidatorfactory(); validator validator = factory.getvalidator(); 

but not suitable build validatorfactory in constructor. time-consuming operation. maybe using cached reference in thrad-local help, not increased complexity.

finally, have decided write validation rules value objects using guava preconditions

 preconditions.checknotnull(value, "value cannot null"); 

Comments