Spring事件处理般过程:
·定义Event类继承org.springframework.context.ApplicationEvent.
·编写发布事件类Publisher实现org.springframework.context.ApplicationContextAware接口.
·覆盖思路方法ApplicationContext(ApplicationContext applicationContext)和发布思路方法publish(Object obj)
·定义时间监听类EventListener实现ApplicationListener接口实现思路方法onApplicationEvent(ApplicationEvent event).
java 代码
import org.springframework.context.ApplicationEvent;
/**
* 定义事件信息
* @author
*
*/
public MessageEvent extends ApplicationEvent {
private String message;
public void Message(String message){
this.message = message;
}
public String getMessage{
message;
}
public MessageEvent(Object source, String message) {
super(source);
this.message = message;
// TODO Auto-generated constructor stub
}
private final long serialVersionUID = 1L;
}
java 代码
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.context.support.FileXmlApplicationContext;
public Publisher implements ApplicationContextAware {
private ApplicationContext context;
@Override
public void ApplicationContext(ApplicationContext arg0)
throws BeansException {
// TODO Auto-generated method stub
this.context = arg0;
}
public void publish(String message){
context.publishEvent( MessageEvent(this,message));
}
public void (String args) {
ApplicationContext ctx = FileXmlApplicationContext("src/applicationContext.xml");
Publisher pub = (Publisher) ctx.getBean("publisher");
pub.publish("Hello World!");
pub.publish("The quick brown fox jumped over the lazy dog");
}
}
java 代码
import org.springframework.context.ApplicationEvent;
import org.springframework.context.ApplicationListener;
public MessageEventListener implements ApplicationListener {
@Override
public void _disibledevent=> .out.prln("Received: " + msEvent.getMessage);
}
}
}
在运行期ApplicationContext会自动在当前所有Bean中寻找ApplicationListener接口实现并将其作为事件接收对象当Application.publishEvent思路方法时所有ApplicationListener接口实现都会被激发每个ApplicationListener可根据事件类型判断是否是自己需要处理事件如上面ActionListener只处理ActionEvent事件
最新评论