Reputation: 12415
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?
Upvotes: 7
Views: 3252
Reputation: 11
Also wanted to mention that the validator is initialized with initialize() per each class.
So if you have DummyClassA and DummyClassB using the SAME validator, initialize will be called twice for each. DummyClassB will initialize its own validator and will not use DummyClassA initialized validator and vice versa. Any new instance of DummyClassA or DummyClassB will use the same validator for each. So if you have four instances of DummyClassA, they will all use the same validator initialized for DummyClassA.
So...DummyClassA has a many to one relationship with a validator and DummyClassB will also have a many to one relationship with a valdiator.
This was something my team and I were curious about when reading the line you read and having concerns of it not being thread safe and such!
Upvotes: 1
Reputation: 18990
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).
Upvotes: 4
Reputation: 242686
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.
Upvotes: 4