Use ManagedBean in FacesConverter
Asked Answered
C

1

5

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?

Cahier answered 13/3, 2013 at 17:55 Comment(0)
A
15

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.

Adrial answered 13/3, 2013 at 18:35 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.