【问题标题】:Use ManagedBean in FacesConverter在 FacesConverter 中使用 ManagedBean
【发布时间】:2013-03-13 17:55:35
【问题描述】:

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

}

我知道galleryContainer 将为空,如果我想将ManagedBean 注入Converter,我也可以将其标记为ManagedBean。问题是我想以漂亮的方式来做,我不想寻找一些“奇怪的解决方案”。也许问题出在我的应用程序中?也许还有其他一些好的解决方案来创建必须从数据库获取数据并在转换器中使用的对象?我还想提一下,我更喜欢使用DependencyInjection,而不是使用new 语句创建新对象(它更容易测试和维护)。有什么建议吗?

【问题讨论】:

    标签: jsf-2 facelets


    【解决方案1】:

    您应该使用@ManagedBean,而不是使用@FacesConverter,因为当前faces 转换器不是有效的注入目标。尽管如此,您可以选择您的转换器作为托管 bean,因此在您的视图中将其称为 converter="#{yourConverter}"(按托管 bean 名称)而不是 converter="yourConverter"(按转换器 id)。

    基本用法示例:

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

    当然,阅读 BalusC 的宝贵意见 Communication in JSF 2.0 也会对这个问题有所了解。

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

    【讨论】:

      猜你喜欢
      • 2014-03-18
      • 2012-06-29
      • 2012-04-25
      • 2012-02-07
      • 2011-07-15
      • 1970-01-01
      • 2015-02-26
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多