I want to use ManagedBean
in my Converter
. The ManagedBean
is responsible for getting data from database. In Converter
I want to convert string into object which must be get from database.
This is my Converter
@FacesConverter(forClass=Gallery.class, value="galleryConverter")
public class GalleryConverter implements Converter {
// of course this one is null
@ManagedProperty(value="#{galleryContainer}")
private GalleryContainer galleryContainer;
@Override
public Object getAsObject(FacesContext context, UIComponent component, String galleryId) {
return galleryContainer.findGallery(galleryId);
...
}
@Override
public String getAsString(FacesContext context, UIComponent component, Object gallery) {
...
}
}
I know that galleryContainer
will be null and if I want to inject ManagedBean
into Converter
I can mark it as ManagedBean
too. The problem is that I want to do it in beautiful way, I don't want to look for some 'strange solution'. Maybe the problem is in my application? Maybe there is some other good solution to create object which must get data from database and used in converter? I want also to mention that I will prefer to use DependencyInjection
instead of creating new object using new
statement (it is easier to test and maintain). Any suggestions?
Instead of using @FacesConverter
you should use @ManagedBean
, because currently faces converter isn't a valid injection target. Nonetheless, you can choose your converter to be a managed bean, thus refer to it in your view as converter="#{yourConverter}"
(by managed bean name) instead of converter="yourConverter"
(by converter id).
Basic usage example:
@ManagedBean
@RequestScoped
public class YourConverter implements Converter {
@ManagedProperty...
...
//implementation of converter methods
}
Of course, reading BalusC's invaluable Communication in JSF 2.0 will shed some light on this question as well.
It is also worth mentioning that the scope of your converter bean may be changed to, for example, application or session, if it is not supposed to hold any state.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With