我想用ManagedBean
in my Converter
. The 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) {
...
}
}
我知道galleryContainer
将为空,如果我想注入ManagedBean
into Converter
我可以将其标记为ManagedBean
也。问题是我想以漂亮的方式做到这一点,我不想寻找一些“奇怪的解决方案”。也许问题出在我的应用程序中?也许还有其他一些好的解决方案来创建必须从数据库获取数据并在转换器中使用的对象?我还想提一下,我更喜欢使用DependencyInjection
而不是使用创建新对象new
声明(更容易测试和维护)。有什么建议么?
而不是使用@FacesConverter
你应该使用@ManagedBean
,因为当前 faces 转换器不是有效的注入目标。尽管如此,您可以选择您的转换器作为托管 bean,因此在您看来将其称为converter="#{yourConverter}"
(按托管 bean 名称)而不是converter="yourConverter"
(通过转换器 ID)。
基本使用示例:
@ManagedBean
@RequestScoped
public class YourConverter implements Converter {
@ManagedProperty...
...
//implementation of converter methods
}
当然,阅读 BalusC 的著作是无价的JSF 2.0 中的通信 http://balusc.blogspot.com/2011/09/communication-in-jsf-20.html#ProcessingGETRequestParameters也将阐明这个问题。
还值得一提的是,如果转换器 bean 不应该保存任何状态,则其范围可能会更改为应用程序或会话等。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)