设计思路:
首先定义一个继承ApplicationEvent的类LogEvent,LogEvent通过ApplicationContext被发布出去.
然后定义一个实现ApplicationListener接口的类LogListener,ApplicationContext会在发布LogEvent事件时通
知LogListener.
接着定义一个实现ApplicationContextAware接口的类Log,通过publishEvent()方法进行事件发布,该方法需
传入LogEvent作为参数,发布时会通知LogListener.
示例代码如下:
//LogEvent.java
package com.gc.action;
import org.springframework.context.ApplicationEvent;
//LogEvent类通过ApplictionContext被发布出去
public class LogEvent extends ApplicationEvent{
public LogEvent(Object msg){
super(msg);
}
}
//LogListener.java
package com.gc.action;
import java.text.SimpleDateFormat;
import java.util.Date;
import org.springframework.context.ApplicationEvent;
import org.springframework.context.ApplicationListener;
public class LogListener implements ApplicationListener{
//ApplicationContext会在发布LogEvent事件时通知LogListener
public void onApplicationEvent(ApplicationEvent event){
if(event instanceof LogEvent){
//设定时间
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
format.setLenient(false);
String currentDate = format.format(new Date());
System.out.println("输出时间: "+currentDate+" 输出内容: "+event.toString());
}
}
}
//Log.java
package com.gc.action;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
public class Log implements ApplicationContextAware{
//设定变量applicationContext
private ApplicationContext applicationContext;
//set方法
public void setApplicationContext(ApplicationContext applicationContext)
throws BeansException{
this.applicationContext = applicationContext;
}
//通过publishEvent发布事件
public int log(String log){
LogEvent event = new LogEvent(log);
this.applicationContext.publishEvent(event);
return 0;
}
}
//配置文件
<?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="log" class="com.gc.action.Log">
</bean>
<bean id="listener" class="com.gc.action.LogListener">
</bean>
</beans>
//TestHelloWorld.java
package com.gc.test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.FileSystemXmlApplicationContext;
import com.gc.action.Log;
public class TestHelloWorld {
public static void main(String[] args) throws InstantiationException,
IllegalAccessException, ClassNotFoundException {
//通过ApplicationContext获取配置文件
ApplicationContext actx = new FileSystemXmlApplicationContext("config.xml");
Log log = (Log)actx.getBean("log");
log.log("test");
}
}
运行结果:
输出时间: 2009-10-31 21:57:57 输出内容: com.gc.action.LogEvent[source=test]