天天看点

Spring 事件处理机制

Spring 本身有[b]ApplicationEvent[/b]和[b]ApplicationListener[/b],ApplicationContext可以发布 ApplicationEvent,然后ApplicationListener监听event并做出相应动作。但是这里的 ApplicationEvent有个陷阱,它的传播范围和当前的ApplicationContext的级别有关,并不是系统中所有的ApplicationListener都可以收到所有的Event。

假设当前系统为一个典型的Struts+Spring+Hibernate系统,那么系统中至少会有两个ApplicationContext 存在,一个时root ApplicationContext,一个是Servlet的ApplicationContext。root ApplicationContext中包含你所有在webApplicationContext.xml中定义的bean,Servlet的 ApplicationContext则包含有所有在action-servlet.xml中定义的bean,需要注意的是root context中的bean是无法看到servlet context中的bean的。而在servlet context中的ApplicationListener也无法收到root context发布的ApplicationEvent。