Java Reference
In-Depth Information
Contexts and Dependency Injection Integration
There have been several integration points between Bean Validation and CDI added with the 1.1 release. This section
will cover each of these integration points and provide examples of how to utilize the integrations.
ValidatorFactory and Validator Injection
The @ValidatorFactory is used to provide initialized instances of Validator to Bean Validation clients. You
would want to obtain a Validator instance so that you could obtain metadata related to a given object or perform
manual validations on bean classes and other objects. If using Bean Validation prior to 1.1, the ValidatorFactory
had to be obtained by calling the Validation.buildDefaultValidatorFactory() method. However, it has been made
easier because the ValidatorFactory can now be injected, as follows:
@Inject ValidatorFactory;
For a bit of background, you may want to obtain a Validator instance so that manual validation can be
performed. The following lines of code demonstrate how to perform manual validation and then parse out the results:
Validator validator = factory.getValidator();
Set<ConstraintViolation<Object>> constraintViolations = validator.validate(o);
for (ConstraintViolation<Object> violation : constraintViolations) {
// do something
}
Depending upon the work that needs to be done, CDI integration makes this process easier once again by
allowing the injection of a Validator as well. To inject a validator, use the same technique as was demonstrated with
the ValidatorFactory injection.
@Inject Validator;
These injections can also be registered as provider-specific by adding a custom qualifier at the injection point.
Using a custom qualifier will help reduce ambiguity in the event that more than one Validator or ValidationFactory
is eligible for injection in a single application. For instance, if you wanted to ensure that injections pertained to a
specific product name of MYPRODUCT , you could inject as follows:
@Inject @MYPRODUCT Validator;
Managed Instances of Requested Classes
If an application requests one of the following classes via XML configuration within the web.xml deployment
descriptor, then an injected ValidationFactory will be configured with managed instances of each of the requested
classes.
ConstraintValidatorFactory
MessageInterpolator
ParameterNameProvider
TransversableResolver
In cases where one or more of the listed classes is registered with an application, the aforementioned managed
instance can be injected into a bean via the @Inject annotation.
 
Search WWH ::




Custom Search