ApplicationEvent
依赖关系
ContextEvent事件机制简介
ContextRefreshedEvent:当整个ApplicationContext容器初始化完毕或者刷新时触发该事件;
@Override
public void refresh() throws BeansException, IllegalStateException {
synchronized (this.startupShutdownMonitor) {
......
try {
......
// Last step: publish corresponding event.
finishRefresh();
}
catch (BeansException ex) {
......
}
}
}
protected void finishRefresh() {
// Initialize lifecycle processor for this context.
initLifecycleProcessor();
// Propagate refresh to lifecycle processor first.
getLifecycleProcessor().onRefresh();
// Publish the final event.
publishEvent(new ContextRefreshedEvent(this));
// Participate in LiveBeansView MBean, if active.
LiveBeansView.registerApplicationContext(this);
}
ContextClosedEvent:当ApplicationContext doClose时触发该事件,这个时候会销毁所有的单例bean;
@Override
public void registerShutdownHook() {
if (this.shutdownHook == null) {
// No shutdown hook registered yet.
this.shutdownHook = new Thread() {
@Override
public void run() {
doClose();
}
};
Runtime.getRuntime().addShutdownHook(this.shutdownHook);
}
}
@Override
public void close() {
synchronized (this.startupShutdownMonitor) {
doClose();
// If we registered a JVM shutdown hook, we don't need it anymore now:
// We've already explicitly closed the context.
if (this.shutdownHook != null) {
try {
Runtime.getRuntime().removeShutdownHook(this.shutdownHook);
}
catch (IllegalStateException ex) {
// ignore - VM is already shutting down
}
}
}
}
protected void doClose() {
if (this.active.get() && this.closed.compareAndSet(false, true)) {
......
try {
// Publish shutdown event.
publishEvent(new ContextClosedEvent(this));
}
catch (Throwable ex) {
logger.warn("Exception thrown from ApplicationListener handling ContextClosedEvent", ex);
}
......
}
}
ContextStartedEvent:当ApplicationContext start时触发该事件;
1 @Override2 public voidstart() {3 getLifecycleProcessor().start();4 publishEvent(new ContextStartedEvent(this));5 }
ContextStoppedEvent:当ApplicationContext stop时触发该事件;
1 @Override2 public voidstop() {3 getLifecycleProcessor().stop();4 publishEvent(new ContextStoppedEvent(this));5 }
ApplicationListener
依赖关系
带你一步步走向源码的世界
从上边打印的线程信息可以知道,spring处理事件通知采用的是当前线程,并没有为为我们启动新的线程,所以,如果需要,你要自己处理线程信息哦,当然也可以设定(如何设置?)!
AbstractApplicationContext
补齐:同一个event,被多个listener监听,先被哪个listener执行是由下边的代码决定的:
如何设置线程池?
回到上边的问题,到底该如何设置线程池呢?
AbstractApplicationEventMulticaster 是private的,并且没有提供写入方法...
实际案例
用在自己的代码里就是最好的例子了 ^_^
Spring 的详细介绍:请点这里
Spring 的下载地址:请点这里