Skip to content
Advertisement

Spring fails to inject entity manager factory

I writing tests for my DAO classes using JPA, with Hibernate as JPA provider, and Spring 3.2. I am not able to inject the entity manager correctly, I get a NullPointerException when trying to access it. My GenericDAO implementation looks like this:

JavaScript

The class of the test looks like this:

JavaScript

My root-context.xml is the following:

JavaScript

I’ve tried several approaches without success, even adding the PersistenceAnnotationBeanPostProcessor as suggested in other SO questions. All other things seem to work fine: Hibernate creates the database tables, the context is loaded, etc. What I am doing wrong?

Edit: the stack trace is the following:

JavaScript

And here is the persistence.xml:

JavaScript

Advertisement

Answer

I’ve finally managed to solve the problem. To instantiate GenericDAO I used an autowired annotation, this way:

JavaScript

but the class where this happens, called DescriptorBO, was instantiated this way:

JavaScript

and thus escaped completely from the control of the Spring container. Changing this into:

JavaScript

and adding the appropriate bean definitions to the root-context.xml:

JavaScript

solved the problem. Now the EntityManager is injected properly.

Lesson learnt: if Spring does not inject the EntityManager (or any other injected object) check that all the object hierarchy above your object is managed by Spring, i. e. instantiated from beans in the application context, either directly or using the Autowired annotation. Check that you do not use the new operator to instantiate any of those objects!!

User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement