CDI support at Converter
and Validator
is in the 2.3
version of JSF, still no release, only milestones .
Such support is provided in the JSR 372 , an integral part of Java EE 8. Then you should use dependencies not yet in release for such support.
To use milestone , use maven , add this dependency:
<dependency>
<groupId>org.glassfish</groupId>
<artifactId>javax.faces</artifactId>
<version>2.3.0-m02</version>
</dependency>
If you do not use maven , do download of JAR
directly from the repository.
Once this is done, an example of convert would be this:
@RequestScoped
@FacesConverter(value = "customConverter", managed = true)
public class CustomConverter implements Converter {
@Inject
private CustomService service;
// implemente getAsString e getAsObject
}
And validator , this:
@RequestScoped
@FacesValidator(value = "customValidator", managed = true)
public class CustomValidator implements Validator {
@Inject
private CustomService service;
// implemente validate
}
Here I put request scope, but you can use the other supported ones as well, if need be.
Note that support was given by adding a new attribute ( managed
) to existing annotations @FacesConverter
and @FacesValidator
.
This is the native support, ie even if it is not convert and validator a bean managed by container CDI it is now eligible for dependency injection.
An important note is: container should be prepared for this, ie be compatible with Java EE 8 (or at least have the latest module of the JSF implementation), otherwise nothing will do any good in this way. For example, in Glassfish Java EE 8 support is provided in version 5. In Glassfish 4 you can try to replace javax.faces.jar
with the JSF 2.3 library mentioned above.
In What's new in JSF 2.3? you can see the news for JSF 2.3, you'll find that some of the news is just increasing CDI support for more JSF artifacts.
Q: The links are from the Java EE 7 documentation because you do not yet have the Java EE 8 documentation.
Editing : Including ways to use in version prior to 2.3
In pre-JSF 2.3, to be able to make use of CDI you will need your bean to be managed by the container to be eligible for dependency injection, so you can use for example @Named
.
For example, our CustomConverter
would look like this:
@Named
@RequestScoped
public class CustomConverter implements Converter {
@Inject
private CustomService service;
// implemente getAsString e getAsObject
}
And our CustomValidator
, like this:
@Named
@RequestScoped
public class CustomValidator implements Validator {
@Inject
private CustomService service;
// implemente validate
}
Also in the version prior to 2.3
, you can use the OmniFaces library that supports CDI, see the example in their documentation.