views:

872

answers:

1

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);
+2  A: 

Try calling

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

where "myEntityManagerFactorBean" is your LocalContainerEntityManagerFactoryBean

But why would you need that?

Bozho
This is a rare situation where I needed to get a different EntityManager depending on values passed in. It's just a unit test which goes through a list of entity managers and ensures that they are all set up properly.
HappyEngineer
ah, for unit tests - ok :)
Bozho