gpt4 book ai didi

java - Spring 父子上下文和应用程序监听器

转载 作者:行者123 更新时间:2023-11-29 05:20:46 24 4
gpt4 key购买 nike

我对 Spring 的 ApplicationListener 在父子上下文方面的性质有疑问。假设您创建了一个父上下文,它创建了一个单例 bean 并注册为 ApplicationListener。然后使用父上下文创建子上下文。当关闭子上下文时,Spring 将发出一个 ContextClosedEvent。此事件是否也传播到父上下文并导致所有作为 ApplicationListener 的父上下文单例接收该事件?

我在文档中注意到一个 [ContextClosedEvent]: ( http://docs.spring.io/spring/docs/4.0.6.RELEASE/spring-framework-reference/htmlsingle/#context-functionality-events ) ,“当 ApplicationContext 关闭时发布,使用 ConfigurableApplicationContext 接口(interface)上的 close() 方法。”这里的“关闭”意味着所有单例 bean 都被销毁. 一个关闭的上下文达到了它的生命终点;它不​​能被刷新或重新启动。”

基本上我要问的是事件发布仅限于特定的子上下文,还是它会传播到所有父/子上下文?

最佳答案

将调用所有监听器,但参数(在本例中为 ContextClosedEvent)将指向正在关闭的上下文。

以下测试创建父上下文、子上下文,启动它们,关闭父上下文,然后关闭子上下文。

public class ContextListenerTest {

@Test
public void contextListenerTest() {
AnnotationConfigApplicationContext parent = new AnnotationConfigApplicationContext(ParentContext.class);
AnnotationConfigApplicationContext child = new AnnotationConfigApplicationContext(ChildContext.class);
child.setParent(parent);
child.start();

System.out.println("closing child now...");
child.close();
System.out.println("closing parent now...");
parent.close();
}

public static class ParentContext {
@Bean
public ApplicationListener<ContextClosedEvent> closeEvent() {
return new ApplicationListener<ContextClosedEvent>() {
@Override
public void onApplicationEvent(ContextClosedEvent event) {
System.out.println("parent listener: " + event);
}
};
}
}

public static class ChildContext {
@Bean
public ApplicationListener<ContextClosedEvent> closeEvent() {
return new ApplicationListener<ContextClosedEvent>() {
@Override
public void onApplicationEvent(ContextClosedEvent event) {
System.out.println("child listener: " + event);
}
};
}
}

}

提供的测试将输出以下文本:

closing child now...
child listener: org.springframework.context.event.ContextClosedEvent[source=org.springframework.context.annotation.AnnotationConfigApplicationContext@3f1b7a14: startup date [Mon Jul 21 15:25:23 BRT 2014]; parent: org.springframework.context.annotation.AnnotationConfigApplicationContext@94ac7e0]
parent listener: org.springframework.context.event.ContextClosedEvent[source=org.springframework.context.annotation.AnnotationConfigApplicationContext@3f1b7a14: startup date [Mon Jul 21 15:25:23 BRT 2014]; parent: org.springframework.context.annotation.AnnotationConfigApplicationContext@94ac7e0]
closing parent now...
parent listener: org.springframework.context.event.ContextClosedEvent[source=org.springframework.context.annotation.AnnotationConfigApplicationContext@94ac7e0: startup date [Mon Jul 21 15:25:22 BRT 2014]; root of context hierarchy]

在第一个关闭(子)中,两个监听器都被执行。但是您可以使用 event.getApplicationContext() 获取正在关闭的上下文。

关于java - Spring 父子上下文和应用程序监听器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24870078/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com