Reading the spec for JSR-303 :
The life cycle of a constraint validation implementation instance is undefined
The initialize method is called by the Bean validation provider prior to any use of the constraint implementation.
The isValid method is evaluated by the Bean Validation provider each time a given value is validated. It returns false if the value is not valid, true otherwise. isValid implementations must be thread-safe.
I cannot quite understand it. initialize is called prior to each isValid call, and isValid should be thread safe? Does it mean I cannot store anything in class level in initialize to access it later from isValid? Specially I need the annotation instance that is passed to initialize.
Can somebody shed light on it please?
It doesn't say that initialize()
should be called before each call of isValid()
. It can be called only once before multiple calls of isValid()
for the same annotation. For example, its javadoc says:
Initialize the validator in preparation for isValid calls.
The initialize()
method is called once for each constraint, while isValid()
is called for every validation of a constraint.
It's perfectly ok to store the annotation (or single attributes of it) passed to isValid()
into a field of the validator and access it later on from isValid()
. You can find an example in the Hibernate Validator reference guide.
You just need to make sure that your isValid()
method may be invocable by several threads in parallel (so for instance you may not alter the state of your validator from within isValid()
without synchronization).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With