Dependency Injection with Spring/Junit/JPA

I'm trying to create JUnit tests for my JPA DAO classes, using Spring 2.5.6 and JUnit 4.8.1.

My test case looks like this:

@ContextConfiguration(locations={"classpath:config/jpaDaoTestsConfig.xml"} )
public class MenuItem_Junit4_JPATest extends BaseJPATestCase {

    private ApplicationContext context;
    private InputStream dataInputStream;
    private IDataSet dataSet;

    private IMenuItemDao menuItemDao;

    public void testFindAll() throws Exception {
        assertEquals(272, menuItemDao.findAll().size());

    ... Other test methods ommitted for brevity ...

I have the following in my jpaDaoTestsConfig.xml:

<?xml version="1.0" encoding="UTF-8"?>

<beans xmlns=""

  <!-- uses the persistence unit defined in the META-INF/persistence.xml JPA configuration file -->
  <bean id="entityManagerFactory" class="org.springframework.orm.jpa.LocalEntityManagerFactoryBean">
        <property name="persistenceUnitName" value="CONOPS_PU" /> 

    <bean id="groupDao" class="" lazy-init="true" />
    <bean id="permissionDao" class="" lazy-init="true" />
    <bean id="applicationUserDao" class="" lazy-init="true" />
    <bean id="conopsUserDao" class="" lazy-init="true" />

    <bean id="menuItemDao" class="" lazy-init="true" />

 <!-- enables interpretation of the @Required annotation to ensure that dependency injection actually occures -->
  <bean class="org.springframework.beans.factory.annotation.RequiredAnnotationBeanPostProcessor"/>  

  <!-- enables interpretation of the @PersistenceUnit/@PersistenceContext annotations providing convenient
       access to EntityManagerFactory/EntityManager -->
  <bean class=""/>

  <!-- transaction manager for use with a single JPA EntityManagerFactory for transactional data access
       to a single datasource -->
  <bean id="jpaTransactionManager" class="org.springframework.orm.jpa.JpaTransactionManager">
      <property name="entityManagerFactory" ref="entityManagerFactory"/>

  <!-- enables interpretation of the @Transactional annotation for declerative transaction managment
       using the specified JpaTransactionManager -->
  <tx:annotation-driven transaction-manager="jpaTransactionManager" proxy-target-class="false"/>


Now, when I try to run this, I get the following:

SEVERE: Caught exception while allowing TestExecutionListener [] to prepare test instance [null(]
org.springframework.beans.factory.BeanCreationException: Error creating bean with name '': Injection of resource fields failed; nested exception is java.lang.IllegalStateException: Specified field type [interface javax.persistence.EntityManagerFactory] is incompatible with resource type [javax.persistence.EntityManager]
    at org.springframework.context.annotation.CommonAnnotationBeanPostProcessor.postProcessAfterInstantiation(
    at org.springframework.test.context.TestContextManager.prepareTestInstance(
    at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.createTest(
    at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.invokeTestMethod(
    at org.junit.internal.runners.JUnit4ClassRunner.runMethods(
    at org.junit.internal.runners.JUnit4ClassRunner$
    at org.junit.internal.runners.ClassRoadie.runUnprotected(
    at org.junit.internal.runners.ClassRoadie.runProtected(
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(
Caused by: java.lang.IllegalStateException: Specified field type [interface javax.persistence.EntityManagerFactory] is incompatible with resource type [javax.persistence.EntityManager]
    at org.springframework.beans.factory.annotation.InjectionMetadata$InjectedElement.checkResourceType(
    at org.springframework.util.ReflectionUtils.doWithFields(
    at org.springframework.util.ReflectionUtils.doWithFields(
    at org.springframework.context.annotation.CommonAnnotationBeanPostProcessor.autowireResource(
    at org.springframework.context.annotation.CommonAnnotationBeanPostProcessor.getResource(
    at org.springframework.context.annotation.CommonAnnotationBeanPostProcessor$ResourceElement.getResourceToInject(
    at org.springframework.beans.factory.annotation.InjectionMetadata$InjectedElement.inject(
    at org.springframework.beans.factory.annotation.InjectionMetadata.injectFields(
    at org.springframework.context.annotation.CommonAnnotationBeanPostProcessor.postProcessAfterInstantiation(
    ... 18 more

It seems to be telling me that its attempting to store an EntityManager object into an EntityManagerFactory field, but I don't understand how or why. My DAO classes accept both an EntityManager and EntityManagerFactory via the @PersistenceContext attribute, and they work find if I load them up and run them without the @ContextConfiguration attribute (i.e. if I just use the XmlApplcationContext to load the DAO and the EntityManagerFactory directly in setUp ()).

Any insights would be appreciated.


These are the correct combinations of annotation + interface:

private EntityManager entityManager;

private EntityManagerFactory entityManagerFactory;

But when using spring's transaction and entity manager support, you don't need the EntityManagerFactory at all.

The reason why you don't need EntityManagerFactory is because the creation of the EntityManager is responsibility of the transaction manager. Here's what happens in short:

  • the transaction manager is triggered before your methods
  • the transaction manager gets the EntityManagerFactory (it is injected in it), creates a new EntityManager, sets in in a ThreadLocal, and starts a new transaction.
  • then it delegates to the service method
  • whenever @PersistenceContext is encountered, a proxy is injected (in your Dao), which, whenever accessed, gets the current EntityManager which has been set in the ThreadLocal

I had to do the below combination, apart from adding spring-aspects jar to the project properties->Aspect Path and enabling spring aspects in sts. Ofcourse in my application context config file i defined the Entitymanagerfactory.

@ContextConfiguration(locations = { "/META-INF/spring/applicationContext-domain.xml" }) public class ReaderTest extends AbstractJUnit4SpringContextTests {

@PersistenceContext private EntityManager entityManager;

I too have same problem, When I added java-persistence api problem got resolved.


Need Your Help

What are the semantics of withValueBackReference?

android android-contentprovider

I cannot figure out the exact semantics of withValueBackReference.

How to add jQueryUI library in MVC 5 project?

jquery jquery-ui

I've just installed Visual Studio 2013 and started new MVC 5 project. I'm kind of new in MVC developing and I can't figure out how to add libraries in my project.