Question

With Spring I can autowire a bean with the following property:

@PersistenceContext(unitName="foo") private EntityManager em;

Using the following I can manually autowire the bean "someBean":

ClassPathXmlApplicationContext ctx = 
      new ClassPathXmlApplicationContext("META-INF/applicationContext.xml");
AutowireCapableBeanFactory fac = ctx.getAutowireCapableBeanFactory();
fac.autowireBean(someBean);

However, I can't figure out how to directly get a particular EntityManager. The use case is that I want to write a test that will get all EntityManager objects and execute simple queries in them to ensure that they are set up properly. To do this I need to be able to get all EntityManager objects from the application context. How can I do that?

The following does not work. It returns an empty map.

Map<String,EntityManager> ems = ctx.getBeansOfType(EntityManager.class);
Was it helpful?

Solution

Try calling

EntitiyManagerFactory factory = 
          (EntityManagerFactory) ctx.getBean("myEntityManagerFactoryBean")
EntityManager em = factory.createEntityManager();

where "myEntityManagerFactorBean" is your LocalContainerEntityManagerFactoryBean

But why would you need that?

OTHER TIPS

I use the SpringJUnit4ClassRunner

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = { "classpath:jndiContext-mock.xml", 
                                    "classpath:spring/testContext.xml" })

The clase under test is injected via the mock context. With this annotated it will get the entity manager via injection.

@PersistenceContext
protected HibernateEntityManager entityManager;
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top