用一个简单的例子来实现spring事件监听的功能
这个例子主要功能是,记录那些用户是第一次登入系统,如果用户是第一次登入系统,则调用spring的事件监听,记录这些用户。
主要用到的spring的类和接口有:
org.springframework.context.event.ApplicationEvent抽象类及其子类来实现事件;
org.springframework.context.ApplicationListener接口及其实现者实现事件的监听。
这两者构成了观察者模式(Observer)。
通过org.springframework.context.ApplicationContextAware接口的实现类,可以取得ApplicationContext, AlicationContext提供了publishEvent方法,实现事件的发布。
下面让我们来看下实现代码:
1 自定义事件 继承ApplicationEvent抽象类
ApplicationEvent 她继承自java.util.EventObject,其中仅仅创建了一个构造器ApplicationEvent,和一个取得当前系统事件的timestamp
public class FirstLoginUserEvent extends ApplicationEvent{
private String loginName;
public FirstLoginUserEvent(Object source){
super(source);
}
public FirstLoginUserEvent(Object source, String loginName){
super(source);
this.loginName=loginName;
System.out.println(super.getTimestamp());
System.out.println(loginName);
}
public String getLoginName(){
return loginName;
}
public void setLoginName(String loginName){
this.loginName=loginName;
}
}
2 定义监听器 继承ApplicationListener接口
@Service("firstLoginUserListener ")
public class FirstLoginUserListener implements ApplicationListener{
private static Log log = LogFactory.getLog(FirstLoginUserListener.class);
public void onApplicationEvent(ApplicationEvent event) {
if (event instanceof FirstLoginUserEvent){
FirstLoginUserEvent firstLoginUserEvent=(FirstLoginUserEvent)
log.debug("用户:"+firstLoginUserEvent.getLoginName()+"第一次登入");
}else{
log.debug("其它事件");
}
}
}
3 发布事件
@Service("userService ")
public class UserService implements ApplicationContextAware {
private ApplicationContext applicationContext;
public void setApplicationContext (ApplicationContext applicationContext){
this.applicationContext=applicationContext;
}
public void decideUser(int num,String loginName){
if (num==0){ //用户第一次登入,发布事件
applicationContext.publishEvent(new FirstLoginUserEvent(this,loginName));
}else{
.......
}
}
}
当我们发布事件的时候,我们的监听器就会对这个事件进行监听。
在有些情况下,比如记录某个特殊操作的日志,可以用spring的事件监听来记录日志,也可以用spring的AOP来做,那么它们之间有什么区别呢? spring事件监听,是以异步方式来操作的,而AOP是同步的。这两种方式那个好呢?就得具体情况具体分析了。