EJB @PersistenceContext EntityManager Throws NullPointerException

后端 未结 1 1199
终归单人心
终归单人心 2021-01-27 05:55

I\'m having a problem with injecting EntityManager by using @PersistenceContext. I try to inject EntityManager in EJB class with @PersistenceContext and I always get NullPointer

相关标签:
1条回答
  • 2021-01-27 06:26

    The EntityManager instance, is injected when the EJB is deployed in the Container. If you take a look at the lifecycle of enterprise bean, you will see clearly when dependency injection occurs. When the Container sees the @Persistencecontext annotation it will inject a container-managed EntityManager.

    The problem is that the code executed in this test is not managed by the Container, therefore, no one inject the necessary dependencies.

    bookDao = new BookEJB();
    

    When you run the test, the BookEJB class is just a simple POJO, the @Stateless and @PersistenceContext annotations are simply ignored.

    You have several alternatives in order to test your EJB, take a look at this link.

    0 讨论(0)
提交回复
热议问题