代码之家  ›  专栏  ›  技术社区  ›  Aaron Digulla

如何将StaticListableBeanFactory连接到ClassPathXmlApplicationContext?

  •  3
  • Aaron Digulla  · 技术社区  · 14 年前

    在我的测试用例设置中,我有以下代码:

        ApplicationContext context = new ClassPathXmlApplicationContext(
                "spring/common.xml"
        );
        StaticListableBeanFactory testBeanFactory = new StaticListableBeanFactory();
    

    如何将两者连接起来,以便测试可以在 testBeanFactory 在安装过程中,应用程序的其余部分使用它们,而不是在 common.xml ?

    注意:我需要混合静态(common.xml)和动态配置。对于后者,我不能使用XML,因为这意味着要写入1000个XML文件。

    2 回复  |  直到 14 年前
        1
  •  3
  •   axtavt    14 年前

    你可以使用 ConfigurableListableBeanFactory.registerSingleton() 而不是 StaticListableBeanFactory.addBean() :

    ApplicationContext context = new ClassPathXmlApplicationContext(
                "spring/common.xml" 
        ); 
    
    GenericApplicationContext child = new GenericApplicationContext(context);
    
    child.getBeanFactory().registerSingleton("foo", ...);
    
        2
  •  0
  •   cyborg    14 年前

    您可能想尝试的另一种选择是使用导入common.xml的bean定义创建test.xml:

    <import resource="spring/common.xml"/>
    
    <bean id="AnIdThatOverridesSomethingInCommon"/>
    

    您只能有一个具有特定ID的bean定义—在同一个文件中,这是一个XML验证错误,在不同的文件中,Spring将重写该定义。

    编辑:刚刚注意到这不适合您的情况-我将把它留在这里完整。