Search code examples
javaspringtomcatjpaspring-annotations

Why does Spring not inject @PersistenceContext entityManager when running on Tomcat vs standalone


I am trying to use Spring to inject @PersistenceContext entityManager into my service. The following configuration works standalone but does not work when deploying on Tomcat. When deploying on Tomcat, the entityManager remains null. My JPA configs are in persistence.xml.

<context:annotation-config />
<tx:annotation-driven/>

<bean id="entityManagerFactory"
    class="org.springframework.beans.factory.config.MethodInvokingFactoryBean">
    <property name="staticMethod">
        <value>javax.persistence.Persistence.createEntityManagerFactory</value>
    </property>
    <property name="arguments">
        <list>
            <value>persistenceUnit</value>
        </list>
    </property>
</bean>

<bean id="transactionManager" class="org.springframework.orm.jpa.JpaTransactionManager">
  <property name="entityManagerFactory" ref="entityManagerFactory"/>
</bean>

What config changes do I need to make for injection to work on Tomcat 6 vs standalone?

Edit: I am able to get the factory inside the service and get an entityManager from it, so persistence.xml settings seem to be working correctly.

Solution: I enabled Spring logging to find the issue -- a missing library. Apparently Spring fails quietly if the above transactionManager bean cannot be created.


Solution

  • If I understand correctly, you must make sure that persistence.xml exist in proper path on your tomact, or more accurate - in your classpath.
    At least I had issues like that when working on enterprise application , so I guess this is a good place to start looking for an answer.
    Did you check the logs? Do they have anything interesting about this?