SeamFramework.orgCommunity Documentation

Chapter 75. Dependency Injection

75.1. Retrieving of validator factory and validators via dependency injection
75.2. Dependency injection for constraint validators

The Seam Validation module provides enhanced support for dependency injection services related to bean validation. This support falls into two areas:

As the Bean Validation API is part of Java EE 6 there is an out-of-the-box support for retrieving validator factories and validators instances via dependency injection in any Java EE 6 container.

The Seam Validation module provides the same service for non-Java EE environments such as for instance stand-alone web containers. Just annotate any field of type javax.validation.ValidatorFactory with @Inject to have the default validator factory injected:

It is also possible to directly inject a validator created by the default validator factory:

The Seam Validation module provides support for dependency injection within javax.validation.ConstraintValidator implementations. This is very useful if you need to access other CDI beans within you constraint validator such as business services etc. In order to make use of dependency injection within a constraint validator implementation it must be a valid bean type as described by the CDI specification, in particular it must be defined within a bean deployment archive.

To make use of dependency injection in constraint validators you have to configure org.jboss.seam.validation.InjectingConstraintValidatorFactory as the constraint validator factory to be used by the bean validation provider. To do so create the file META-INF/validation.xml with the following contents:

Having configured the constraint validator factory you can inject arbitrary CDI beans into you validator implementations. Listing Example 75.4, “Dependency injection within ConstraintValidator implementation” shows a ConstraintValidator implementation for the @Past constraint which uses an injected time service instead of relying on the JVM's current time to determine whether a given date is in the past or not.