Reputation: 792
I'm having problems with CDI on tomcat. That's some relevant part of my code:
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();
}
}
My DAO Class:
public class DAO<T> implements Serializable{
private final Class<T> classe;
@Inject
protected EntityManager em;
public DAO(Class<T> classe) {
this.classe = classe;
}
}
and a child class:
public class UserDao extends DAO<User> implements Serializable{
public UserDao() {
super(User.class);
}
}
Because of the Generics, I used a producer for the DAO class:
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);
}
}
In this example:
public class Test {
@Inject UserDAO userDAO;
@Inject DAO<User> dao;
}
When I try to use the UserDAO class, everything works fine, but when I use the DAO, the EntityManager remains null. Anyone have any idea?
Upvotes: 1
Views: 2188
Reputation: 1520
In DAOFactory
you instantiate the DAO with new
operator, if you do so, CDI has no chance to inject dependencies in the DAO instance.
While in UserDAO
CDI manages the entity manager injection.
So in DAOFactory
you should set manually the entity manager in the newly created DAO instance.
Upvotes: 5