【问题标题】:In Spring, how do I use a ClassPathXmlApplicationContext to get an EntityManager?在 Spring 中,如何使用 ClassPathXmlApplicationContext 来获取 EntityManager?
【发布时间】:2009-12-11 22:37:30
【问题描述】:

使用 Spring,我可以自动装配具有以下属性的 bean:

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

使用以下内容我可以手动自动装配 bean“someBean”:

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

但是,我无法弄清楚如何直接获取特定的 EntityManager。用例是我想编写一个测试,它将获取所有 EntityManager 对象并在其中执行简单的查询以确保它们设置正确。为此,我需要能够从应用程序上下文中获取所有 EntityManager 对象。我该怎么做?

以下不起作用。它返回一个空地图。

Map<String,EntityManager> ems = ctx.getBeansOfType(EntityManager.class);

【问题讨论】:

    标签: spring entitymanager


    【解决方案1】:

    尝试调用

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

    其中“myEntityManagerFactorBean”是您的LocalContainerEntityManagerFactoryBean

    但是你为什么需要它呢?

    【讨论】:

    • 这是一种罕见的情况,我需要根据传入的值获取不同的 EntityManager。这只是一个单元测试,它通过实体管理器列表并确保它们都正确设置。
    【解决方案2】:

    我使用 SpringJUnit4ClassRunner

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

    被测类是通过模拟上下文注入的。有了这个注解,它将通过注入获得实体管理器。

    @PersistenceContext
    protected HibernateEntityManager entityManager;
    

    【讨论】:

      猜你喜欢
      • 2011-05-16
      • 2013-09-11
      • 2014-05-16
      • 1970-01-01
      • 2014-10-05
      • 2015-11-08
      • 1970-01-01
      • 2016-06-17
      • 2014-12-14
      相关资源
      最近更新 更多