applicationContext 的事件机制是观察者设计模式,通过ApplicationEvent 类,和ApplicationListener 接口,可以实现ApplicationContext 的事件处理,如果容器中有一个ApplicationListener Bean每当ApplicationContext发布ApplicationEvent时,ApplicationListener Bean将自动被触发:
Spring 内置事件:
- ContextRefreshedEvent:当ApplicationContext初始化或者刷新时触发该事件。
- ContextClosedEvent:当ApplicationContext被关闭时触发该事件。容器被关闭时,其管理的所有单例Bean都被销毁。
- RequestHandleEvent:在Web应用中,当一个http请求(request)结束触发该事件。
- ContestStartedEvent:Spring2.5新增的事件,当容器调用ConfigurableApplicationContext的Start()方法开始/重新开始容器时触发该事件。
- ContestStopedEvent:Spring2.5新增的事件,当容器调用ConfigurableApplicationContext的Stop()方法停止容器时触发该事件。
- SessionConnectedEvent 为WebSocket 功能服务
- SessionConnectEvent 为WebSocket 功能服务
- SessionDisconnectEvnet 为WebSocket 功能服务
例1
监听当spring容器的启动
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.ApplicationListener;
import org.springframework.context.event.ContextRefreshedEvent;
import org.springframework.stereotype.Component;
@Component
public class SpringRefreshedEventListener implements ApplicationListener<ContextRefreshedEvent> {
private final Logger logger = LoggerFactory.getLogger(SpringRefreshedEventListener.class);
@Override
public void onApplicationEvent(ContextRefreshedEvent contextRefreshedEvent) {
logger.debug("spring 容器已经就绪。。。。");
}
}
例2:
发布事件:
//自定义事件
import org.springframework.context.ApplicationEvent;
public class MyEvent extends ApplicationEvent {
public MyEvent(Object source) {
super(source);
}
}
//发布自定义事件
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;
@Component
public class MyEventPublisher implements ApplicationContextAware {
private ApplicationContext applicationContext;
public void publish(){
MyEvent myEvent = new MyEvent(null);
applicationContext.publishEvent(myEvent);
}
@Override
public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
this.applicationContext = applicationContext;
}
}
例3
发布事件:
Publisher类实现 org.springframework.context.ApplicationEventPublisherAware 接口
import org.springframework.context.ApplicationEventPublisher;
import org.springframework.context.ApplicationEventPublisherAware;
import org.springframework.stereotype.Component;
@Component
public class MyEventPublisherII implements ApplicationEventPublisherAware {
private ApplicationEventPublisher applicationEventPublisher;
public void publish(){
MyEvent myEvent = new MyEvent(null);
applicationEventPublisher.publishEvent(myEvent);
}
@Override
public void setApplicationEventPublisher(ApplicationEventPublisher applicationEventPublisher) {
this.applicationEventPublisher = applicationEventPublisher;
}
}