Use ManagedBean in FacesConverter

I want to use ManagedBean in my Converter . ManagedBean is responsible for retrieving data from the database. In Converter I want to convert a string to an object that should be retrieved from the 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 insert a ManagedBean into Converter , I can mark it as a ManagedBean too. The problem is that I want to do it beautifully, I don’t want to look for some kind of “strange solution”. Maybe the problem is in my application? Maybe there is another good solution for creating an object that should receive data from the database and be used in the converter? I also want to mention that I prefer to use DependencyInjection instead of creating a new object using the new operator (it is easier to test and maintain). Any suggestions?

+4
source share
1 answer

Instead of using @FacesConverter you should use @ManagedBean , because currently a data converter is not a valid injection target. However, you can choose to have your converter bean controlled, so refer to it in your view as converter="#{yourConverter}" (bean controlled name) instead of converter="yourConverter" (by converter identifier).

Basic Usage Example:

 @ManagedBean @RequestScoped public class YourConverter implements Converter { @ManagedProperty... ... //implementation of converter methods } 

Of course, reading the invaluable information about BalusC Communications in JSF 2.0 also sheds light on this issue.

It is also worth noting that the scope of your bean converter can be changed, for example, to an application or session if it should not contain any state.

+13
source

Source: https://habr.com/ru/post/1469041/


All Articles