marți, 10 februarie 2015

JSF 2.3 - Using a CDI managed Validator / Converter

Using @Inject in JSF custom validators/converters can be very useful, but until JSF 2.3 was not supported. Nevertheless, in JSF 2.2.x (e.g. 2.2.7) you can use @Inject in a custom validator, as below:

import javax.inject.Inject;
...
@FacesValidator(value="myValidator")
public class MyValidator implements Validator {

    @Inject
    SomeBean someBean;
    ...
}

And, in a custom converter also:

import javax.inject.Inject;
...
@FacesConverter(value="myConverter")
public class MyConverter implements Converter{
   
    @Inject
    SomeBean someBean;

    ...
}

Even if the above approaches work fine, there are not listed (recommended to be used) as JSF 2.2 features. But, starting with JSF 2.3, validators and converters can be managed by CDI. For this, we just use a flag attribute named, managed, as below:

import javax.inject.Inject;
...
@FacesValidator(value="myValidator", managed=true)
public class MyValidator implements Validator {

    @Inject
    SomeBean someBean;
    ...
}

import javax.inject.Inject;
...
@FacesConverter(value="myConverter", managed=true)
public class MyConverter implements Converter{
   
    @Inject
    SomeBean someBean;

    ...
}

So, if the validators/converters will be managed by CDI, we can safely use the @Inject.

You can read more about this on this Java EE 8 ZEEF page and on this Java.net (CDI Validator | CDI Converter).

Until JSF 2.3 will be officially released, you can follow JSF 2.3 development via GitHub mirror, and/or try to build JSF Jars from SVN.

Niciun comentariu:

Trimiteți un comentariu