spring的事件流程如下:
1.自己的event需要继承 ApplicationEvent,并且写相应的构造函数
2.定义一个监听器listener,实现ApplicationListener接口,重写onApplicationEvent方法
3.使用ApplicationContext容器发布事件,监听器listener在Bean中
如果容器中有一个ApplicationListener Bean,每当ApplicationContext发布ApplicationEvent时,ApplicationListener Bean将自动被触发。
Spring的事件机制与所有时间机制都基本相似,它们都需要事件源、事件和事件监听器组成。只是此处的事件源是ApplicationContext,且事件必须由Java程序显式触发。
ApplicationContext?
它是Spring的核心,Context我们通常解释为上下文环境,但是理解成容器会更好些。
ApplicationContext则是应用的容器。
Spring把Bean放在容器中,需要用就通过get方法取出来。
详见:Spring ApplicationContext 容器
ApplicationEvent
ApplicationEvent:容器事件,必须由ApplicationContext发布
是个抽象类,里面只有一个构造函数和一个长整型的timestamp。
ApplicationListener
ApplicationListener:监听器,可由容器中的任何监听器Bean担任
ApplicationListener是一个接口,里面只有一个onApplicationEvent
方法。
所以自己的类在实现该接口的时候,要实现该方法。把需要处理的操作放在onApplicationEvent中进行处理:
implements ApplicationListener的类就是一个事件监听器,它会实现onApplicationEvent方法,当
它检测到一个extends ApplicationEvent 的类后(需要对哪个类进行监听需要自己在onApplicationEvent里设置:event instanceof <类名>),就做出一些操作。
在一些业务场景中,当容器初始化完成之后,需要处理一些操作,比如一些数据的加载、初始化缓存、特定任务的注册等等。这个时候我们就可以使用Spring提供的ApplicationListener来进行操作。
示例
import org.springframework.context.ApplicationEvent;
public class Event extends ApplicationEvent
{
public String text;
public Event(Object source)
{
super(source);
}
public Event(Object source,String text) {
super(source);
this.text = text;
}
public void print()
{
System.out.println("hello world!");
}
}
监听器:
import org.springframework.context.ApplicationEvent;
import org.springframework.context.ApplicationListener;
public class EventListener implements ApplicationListener
{
public void onApplicationEvent(ApplicationEvent event)
{
if(event instanceof Event)
{
Event myEvent = (Event)event;
myEvent .print();
System.out.println("the source is:"+myEvent .getSource());
System.out.println("the text is:"+myEvent .text);
}
}
}
applicationContext.xml文件配置:
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd">
<bean id="eventListener" class="Spring事件.EventListener"></bean>
</beans>
测试类:
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class Test
{
public static void main(String[] args)
{
ApplicationContext context = new ClassPathXmlApplicationContext("Spring事件//Beans.xml");//ApplicationContext 容器,Beans中有EventListener
Event event = new Event("hello","this is text!");//实现Event 类,触发EventListener事件
context.publishEvent(event);
//主动触发该事件
//context.publishEvent(event);
}
}
测试结果:
hello world!
the source is:hello
the text is:this is text!