Java 使用上下文层次结构子上下文bean作为应用程序侦听器的Spring集成测试

Java 使用上下文层次结构子上下文bean作为应用程序侦听器的Spring集成测试,java,spring,junit,Java,Spring,Junit,我是春天的新手,如果我做了傻事,请原谅我。我正在尝试为使用spring的应用程序编写一个集成测试 我正在创建一个上下文层次结构,如下所示 @Before public void setup(){ parentContext = new AnnotationConfigApplicationContext(TestConfig.class); // some more setup stuff here } 在我的测试方法中,我试图创建一个新的子上下文,它只有一个b

我是春天的新手,如果我做了傻事,请原谅我。我正在尝试为使用spring的应用程序编写一个集成测试

我正在创建一个上下文层次结构,如下所示

  @Before
  public void setup(){
     parentContext = new AnnotationConfigApplicationContext(TestConfig.class);
     // some more setup stuff here
  }
在我的测试方法中,我试图创建一个新的子上下文,它只有一个bean,它是一个应用程序侦听器,依赖于父方法中的bean

public void test(){
    childContext = new AnnotationConfigApplicationContext();
    childContext.setParent(ctx);
    register(TestConfig2.class);
    childContext.refresh();
    // some testing stuff here that generates events
}
我面临的问题是,来自子上下文的bean没有得到应用程序事件的通知,而且@Value注释也没有得到处理

我做错了什么?

声明

private static ClassPathXmlApplicationContext context;
在方法@之前

@BeforeClass
public static void setUpBeforeClass() throws Exception {
    context = new ClassPathXmlApplicationContext("/WEB-INF/application-Context.xml");
}
在methode@After

@AfterClass
public static void tearDownAfterClass() throws Exception {
    context.close();
}
你的方法测试

@Test
public void Test() {
    //Your Code Here
}

我也将在春天开始

事实上,我发现了哪里出了问题。我的事件发布者位于父上下文中。我在spring论坛上读到,spring上下文层次结构就像类加载器一样工作。正如在子上下文加载的任何bean中一样,父上下文不可见

parentContext.addApplicationListener(messageListener);
因此,我必须手动将applicationlistener添加到父上下文中

parentContext.addApplicationListener(messageListener);
如果希望我的childContext bean从parentContext获取属性,我必须将parentContext的PropertyPlaceHolderConfigure添加为BeanFactory后处理器

  configurer = parentContext.getBean(PropertyPlaceholderConfigurer.class);
  childContext.addBeanFactoryPostProcessor(configurer);
总而言之,我必须在我的测试方法中做到以下几点

public void test(){
    childContext = new AnnotationConfigApplicationContext();
    childContext.setParent(parentContext);
    register(TestConfig2.class);
    configurer = parentContext.getBean(PropertyPlaceholderConfigurer.class);
    childContext.addBeanFactoryPostProcessor(configurer);
    childContext.refresh();

    MessageListener messageListener = childContext.getBean(MessageListener.class);
    parentContext.addApplicationListener(messageListener);

    // some testing stuff here that generates events
}

我需要两个不同的上下文。一个是我所有bean的主上下文。我的第二个上下文是另一个bean。