我在tomcat上遇到CDI问题。这是我的代码的一些相关部分:
public class JPAUtil {
private static EntityManagerFactory emf = Persistence.createEntityManagerFactory("unit");
@Produces @RequestScoped
public static EntityManager getEntityManager() {
return emf.createEntityManager();
}
public void close(@Disposes EntityManager em) {
em.close();
}
}
我的 DAO 课程:
public class DAO<T> implements Serializable{
private final Class<T> classe;
@Inject
protected EntityManager em;
public DAO(Class<T> classe) {
this.classe = classe;
}
}
和一个子类:
public class UserDao extends DAO<User> implements Serializable{
public UserDao() {
super(User.class);
}
}
由于泛型,我为 DAO 类使用了生产者:
public class DAOFactory {
@Produces
@SuppressWarnings({ "rawtypes", "unchecked" })
public DAO createDAO(InjectionPoint injectionPoint) {
ParameterizedType type = (ParameterizedType) injectionPoint.getType();
Class classe = (Class) type.getActualTypeArguments()[0];
return new DAO(classe);
}
}
在这个例子中:
public class Test {
@Inject UserDAO userDAO;
@Inject DAO<User> dao;
}
当我尝试使用 UserDAO 类时,一切正常,但是当我使用 DAO 时,EntityManager 仍然为空。有人知道吗?