开发者

In Spring, how do I use a ClassPathXmlApplicationContext to get an EntityManager?

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 fr开发者_开发知识库om 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);


Try calling

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

where "myEntityManagerFactorBean" is your LocalContainerEntityManagerFactoryBean

But why would you need that?


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;
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜