title: Can I inject an JPA EntityManager using CDI and @PersistenceContext, like with Spring?
body: <p>In Spring, I can inject an <a href="http://docs.oracle.com/javaee/7/api/javax/persistence/EntityManager.html" rel="nofollow noreferrer"><code>javax.persistence.EntityManager</code></a>
  into a Spring bean using the annotation <code>@javax.persistence.PersistenceContext</code>, like this:</p>
  
  <pre><code>@Service
  public class MyRepository {
      @PersistenceContext
      private EntityManager entityManager;
  }
  </code></pre>
  
  <p>This is documented in the Spring docs in chapter <a href="http://docs.spring.io/spring/docs/4.3.3.RELEASE/spring-framework-reference/html/orm.html#orm-jpa-straight" rel="nofollow noreferrer">20.5.2 Implementing DAOs based on plain JPA</a>.</p>
  
  <p>Is there a way to do this using CDI (specifically, Weld) if I am not using a Java EE container?</p>
  
  <p>In particular, is it possible to reuse the annotation <code>@PersistenceContext</code> for CDI (because existing code uses it with Spring) ?</p>
  
  <p>As far as I understand: When using a Java EE container, the container will interpret the annotation and inject an EntityManager. Is that correct? And is there a way to get this to work using Weld, but without a Java EE container?</p>
  
  <hr>
  
  <p>I tried to inject the class above into another class using Weld (in Tomcat, without Java EE). The injection takes place, so Weld correctly creates an instance of <code>MyRepository</code>, however the field <code>MyRepository.entityManager</code> is <code>null</code>, as if the annotation <code>@PersistenceContext</code> was ignored.</p>
  
  <p>What is happening (or rather, not happening) here?</p>