The CDI support in Converter
and Validator
is in the version 2.3
JSF, still release, only Milestones.
Such support is provided for in JSR 372, integral part of Java EE 8. So you should use dependencies not yet in version release for such support.
To make use of Milestone, if use Maven, add this dependency:
<dependency>
<groupId>org.glassfish</groupId>
<artifactId>javax.faces</artifactId>
<version>2.3.0-m02</version>
</dependency>
If not use Maven, do the download of JAR
directly from the repository.
Done this, 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 of Validator, this:
@RequestScoped
@FacesValidator(value = "customValidator", managed = true)
public class CustomValidator implements Validator {
@Inject
private CustomService service;
// implemente validate
}
Here I put the request scope, but you can use the other supported ones too, if you need.
Note that support was given by including a new attribute (managed
) to existing annotations @FacesConverter
and @FacesValidator
.
This is the support native, that is, even if it is not convert and Validator one bean managed by container CDI it is now eligible for dependency injection.
An important observation is: the 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 it will do no good to use this way. For example, in Glassfish support for Java EE 8 is provided in version 5. In Glassfish 4 you can try to replace javax.faces.jar
by the JSF 2.3 library cited above.
In What’s new in JSF 2.3? you can see the news for JSF 2.3, you will see that some of the novelties is precisely the increase of CDI support to more JSF artifacts.
P.S.: the links are from the Java EE 7 documentation because it does not have the Java EE 8 documentation yet.
Editing: including ways to use in a version prior to 2.3
In version prior to JSF 2.3, to be able to make use of CDI you will need your bean is managed by container to be eligible for addiction 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
, thus:
@Named
@RequestScoped
public class CustomValidator implements Validator {
@Inject
private CustomService service;
// implemente validate
}
Also in version prior to 2.3
, you can use the library Omnifaces that supports CDI, see example in their documentation.
What have you tried?
– falsarella
@Ozelo Be more specific, in more detail. Which container you are using, what are your configuration files, what is the Java version? Where was that said? What do you want to do?
– Filipe Miranda