我正在编写我的第一个Java EE 6 Web应用程序作为学习练习.我没有使用框架,只有JPA 2.0,EJB 3.1和JSF 2.0.
我有一个自定义转换器将存储在SelectOne组件中的JPA实体转换回实体.我正在使用InitialContext.lookup来获取对会话Bean的引用以查找相关的实体.
我想创建一个通用的实体转换器,所以我不必为每个实体创建一个转换器.我以为我会创建一个抽象实体并让所有实体扩展它.然后为抽象实体创建自定义转换器,并将其用作所有实体的转换器.
这听起来是否合理和/或切实可行?
是不是有一个抽象的实体,只是一个转换器来转换任何实体更有意义?在那种情况下,我不确定如何获得对相应会话Bean的引用.
我已经包含了我当前的转换器,因为我不确定我是否以最有效的方式获取对Session Bean的引用.
package com.mycom.rentalstore.converters;
import com.mycom.rentalstore.ejbs.ClassificationEJB;
import com.mycom.rentalstore.entities.Classification;
import javax.faces.application.FacesMessage;
import javax.faces.component.UIComponent;
import javax.faces.context.FacesContext;
import javax.faces.convert.Converter;
import javax.faces.convert.ConverterException;
import javax.faces.convert.FacesConverter;
import javax.naming.InitialContext;
import javax.naming.NamingException;
@FacesConverter(forClass = Classification.class)
public class ClassificationConverter implements Converter {
private InitialContext ic;
private ClassificationEJB classificationEJB;
@Override
public Object getAsObject(FacesContext context, UIComponent component, String value) {
try {
ic = new InitialContext();
classificationEJB = (ClassificationEJB) ic.lookup("java:global/com.mycom.rentalstore_RentalStore_war_1.0-SNAPSHOT/ClassificationEJB");
} catch (NamingException e) {
throw new ConverterException(new FacesMessage(String.format("Cannot obtain …Run Code Online (Sandbox Code Playgroud) 我正在使用Spring和Hibernate开发JSF项目,其中包括许多Converter遵循相同模式的s:
getAsObject 接收对象id的字符串表示形式,将其转换为数字,并获取给定种类的实体和给定的id
getAsString receive和entity并返回转换为的对象的id String
代码基本上是以下内容(省略检查):
@ManagedBean(name="myConverter")
@SessionScoped
public class MyConverter implements Converter {
private MyService myService;
/* ... */
@Override
public Object getAsObject(FacesContext facesContext, UIComponent uiComponent, String value) {
int id = Integer.parseInt(value);
return myService.getById(id);
}
@Override
public String getAsString(FacesContext facesContext, UIComponent uiComponent, Object value) {
return ((MyEntity)value).getId().toString();
}
}
Run Code Online (Sandbox Code Playgroud)
鉴于大量的ConverterS中的完全一样(除了类型MyService和MyEntity当然的),我想知道,如果它使用一个通用的转换器是值得的.通用本身的实现并不困难,但我不确定声明Beans的正确方法.
可能的解决方案如下:
1 - 编写通用实现,让我们调用它MyGenericConverter,不需要任何Bean注释
2 - 将特定转换器ad写为子类,MyGenericConverter<T>并根据需要对其进行注释:
@ManagedBean(name="myFooConverter")
@SessionScoped
public class MyFooConverter implements MyGenericConverter<Foo> { …Run Code Online (Sandbox Code Playgroud)