public class HierarchicalEventPropagationListener implements ApplicationListener<HierarchicalEventPropagationEvent> {
private String listenerId;
public HierarchicalEventPropagationListener(String listenerId) {
this.listenerId = listenerId;
}
@Override
public void onApplicationEvent(HierarchicalEventPropagationEvent event) {
System.out.println(listenerId + " received event - " + event.getMessage());
}
}
复制代码
为了测试继承机制,我们需要构建主容器和子容器,并为每个容器注册了一个监听器。初始化容器后,我们在两个容器中分别发布事件。
请注意,首先需要刷新主容器,然后刷新子容器。否则会出现异常:Exception in thread "main" java.lang.IllegalStateException: ApplicationEventMulticaster not initialized - call 'refresh' before multicasting events via the context: org.springframework.context.annotation.AnnotationConfigApplicationContext@somehashcode
主程序如下: