问题
I have a Java web service module and ejb modulein netbeans (All part of an enterprise application). the web service is consuming the ejb class using @EJB injection. Inside the ejb module i have a TransactionManager class which is not an enterprise bean. just a POJO class. I am trying to inject the EntityManager using
@PersistanceContext(unitName = "testPU")
EntityManager em;
but the em is allways null. I am calling the TransactionManager class from by bean, and if i declare the EntityManager declaration in bean class, it injects just fine in the bean class. but in POJO it is always null.
I am new to EJB (using version JEE7) . can u please guide me ?
Reply to Shailendra : my bean and pojo are in the same jar file, and it has the bean.xml and persistence.xml. I tried to make the TransactionManager class as bean, using @Stateless and @Local, but there are some pojo classes in between the ejb class and the TransactionManager class, and when i tried to access the TransactionManager class from its parent pojo class using @EJB TransactionManager transactionManager; this object too returned null.
Dear Shilendra, thanks for the reply Below is my EJB class
@Stateless
@Local(IMyService.class)
public class MyService extends MyBase implements IMyService
{
MyComponent component = null;
public void doSomething(X x)
{
component = new MyComponent();
component.doSomething(x);
}
}
I have a POJO class as MyComponent
public class MyComponent extends MyBase implements IMyComponent
{
TransactionManager tManager = null;
public void doSomething(X x)
{
tManager = new TransactionManager();
tManager.doSomething(x);
}
}
And The TransactionManager class is the class that i want Dependency Injection done for PersistenceContext
public class TransactionManager extends MyBase implements ITransactionManager
{
@PersistenceContext(unitName="TestPU")
EntityManager em;
public void doSomething(X x)
{
em.persist(x);
}
}
回答1:
POJO isn't managed by the container. Whereas the bean is managed by the container & is responsible for injecting resources.
You can try JNDI lookup to lookup resources for non-managed custom classes for which container isn't responsible.
回答2:
The reason is be that your POJO is not managed by the container. If your container supports CDI (Context dependency injection) then declare your bean in a bean archive (have beans.xml in META-INF or WEB-INF) in order to be managed.
来源:https://stackoverflow.com/questions/19397822/entitymanager-is-null-inside-pojo-class-in-ejb-container