今天尝试如何截取ApplicationContext的事件,走了一些弯路,弄明白后马上写下来,给自己和别人在遇到类似事情是做个参考。
项目结构如图:
其中,ContextEvent继承了ApplicationEvent抽象类,其中需实现一个带Object参数的构造函数,这个Object参数表示的是事件源。
ContextListener实现了ApplicationListener接口,经过配置文件中的定义后,在ContextListener中处理事件。
Demo是主类,HelloBean这里没用。
如何获得事件监听:
Bean定义文件中需要这么一条语句:
<bean id="listener" class="onlytest.five00.ContextListener"/>
注意:红字部分表示的是项目中的包,这样你才可以自己设置数据源并且交给ContextListener处理
如何给ApplicationContext添加事件:
ApplicationContext有一个方法---publishEvent(new XXXEvent(ApplicationContext context));
ApplicationEvent有很多子类,比如:
1.ContextClosedEvent:ApplicationContext关闭时发布事件
2.ContextRefreshedEvent:ApplicationContext初始化或者Refershed时发布事件
3.RequestHandledEvent:在Web应用程序中,当请求被处理时,ApplicationContext会发布此事件。
同样的,你也可以自己定义一个事件源,比如可以用字符串来定义,方法是
publishEvent(String str);
其实publishEvent中的参数是Object型的
截获事件并处理:
ContextListener因为实现了ApplicationListener接口,所以必须实现一个
onAoolicationEvent(ApplicationEvent e){}方法,通过e.getSource获得事件源,也可以用instanceof来比较是ApplicationEvent的那一种事件类型。
具体代码:
ContextEvent:
package onlytest.five00;
import org.springframework.context.ApplicationEvent;
public class ContextEvent extends ApplicationEvent{
/**
*
*/
private static final long serialVersionUID = 1L;
public ContextEvent(Object arg0) {
super(arg0);
System.out.println("e.source is ");
// TODO Auto-generated constructor stub
}
}
ContextListener:
package onlytest.five00;
import org.springframework.context.ApplicationEvent;
import org.springframework.context.ApplicationListener;
import org.springframework.context.event.ContextClosedEvent;
public class ContextListener implements ApplicationListener{
public void onApplicationEvent(ApplicationEvent e) {
// TODO Auto-generated method stub
System.out.println("e.source is "+e.getSource());
//获得字符串事件源
if(((e.getSource()).toString()).equals("test"))
{
System.out.println("context test!");
}
//获得ApplicationEvent事件源
else if(e instanceof ContextClosedEvent)
{
System.out.println("context closed!");
}
}
}
Demo
package onlytest.five00;
import org.springframework.context.ApplicationContext;
import org.springframework.context.event.ContextClosedEvent;
import org.springframework.context.support.FileSystemXmlApplicationContext;
public class Demo{
public static void main(String args[])
{
ApplicationContext context=
new FileSystemXmlApplicationContext("beans.xml");
//字符串当事件源
context.publishEvent(new ContextEvent("test"));
//ApplicationEvent当事件源
context.publishEvent(new ContextClosedEvent(context));
}
}
beans.xml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN//EN" "http://www.springframework.org/dtd/spring-beans.dtd" >
<beans>
<bean id="listener"
class="onlytest.five00.ContextListener"/>
<bean id="HelloBean" class="onlytest.five00.HelloBean">
<constructor-arg index="0">
<value>Five00</value>
</constructor-arg>
<constructor-arg index="1">
<value>YE!!</value>
</constructor-arg>
</bean>
</beans>