在FacesConverter中使用ManagedBean

pep*_*uch 4 facelets jsf-2

我想用ManagedBean在我的Converter.该ManagedBean负责从数据库中获取数据.在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) {
        ...
    }

}
Run Code Online (Sandbox Code Playgroud)

我知道这galleryContainer将是无效的,如果我要注入ManagedBeanConverter我可以将其标记为ManagedBean过.问题是我想以漂亮的方式做到这一点,我不想寻找一些"奇怪的解决方案".也许问题出在我的申请表中?也许有一些其他好的解决方案来创建必须从数据库获取数据并在转换器中使用的对象?我还想提一下,我宁愿使用DependencyInjection而不是使用new语句创建新对象(它更容易测试和维护).有什么建议?

sku*_*sel 13

而不是使用@FacesConverter你应该使用@ManagedBean,因为目前面对转换器不是一个有效的注入目标.尽管如此,您可以选择将转换器作为托管bean,因此在您的视图中将其引用为converter="#{yourConverter}"(通过托管bean名称)而不是converter="yourConverter"(通过转换器ID).

基本用法示例:

@ManagedBean
@RequestScoped
public class YourConverter implements Converter {

    @ManagedProperty...
    ...

    //implementation of converter methods

}
Run Code Online (Sandbox Code Playgroud)

当然,阅读BalusC 在JSF 2.0中的宝贵通信也将为这个问题提供一些启示.

还值得一提的是,如果转换器bean不应该保持任何状态,那么转换器bean的范围可能会更改为,例如,应用程序或会话.