[英]Spring Integration Expression For Bean References on Application Context
[英]Spring integration test with context hierarchy child context bean as application listener
我是Spring的新手,如果我做傻事,请原谅我。 我正在尝试为使用spring的应用程序编写集成测试。
我正在创建一个上下文层次结构,如下
@Before
public void setup(){
parentContext = new AnnotationConfigApplicationContext(TestConfig.class);
// some more setup stuff here
}
在我的测试方法中,我试图创建一个只有一个bean的新子上下文,该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;
在方法@Before
@BeforeClass
public static void setUpBeforeClass() throws Exception {
context = new ClassPathXmlApplicationContext("/WEB-INF/application-Context.xml");
}
在方法之后
@AfterClass
public static void tearDownAfterClass() throws Exception {
context.close();
}
您的方法测试
@Test
public void Test() {
//Your Code Here
}
我也在春天开始
实际上,我知道出了什么问题。 我的事件发布者是在父上下文中。 我在Spring论坛上读到,Spring上下文层次结构像类加载器一样工作。 如同在子上下文加载的任何bean中一样,父上下文不可见。
因此,我不得不手动将applicationlistener添加到父上下文中。
parentContext.addApplicationListener(messageListener);
如果要让childContext bean从parentContext获取属性,则必须添加parentContext的PropertyPlaceholderConfigurer作为beanFactoryPostProcessor。
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
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.