Spring源码-LifecycleProcessor

使用方法

Lifecycle:容器的生命周期回调,容器启动之后运行到某些节点(容器start/stop时候)可以回调Lifecycle子类的方法。比如在容器启动后初始化资源池,在容器停止时候调用资源池销毁的动作

我们实现Lifecycle中接口。注:建议实现SmartLifecycle接口,因为它Lifecycle接口的加强接口,默认实现了stop(Runnable callback),在调用中通过一个CountdownLatch来异步处理stop,SmartLifecycle非常不建议实现stop(Runnable callback)方法

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
  public interface Lifecycle {
void start();
void stop();
boolean isRunning();
}

public interface Phased {
int getPhase();
}

public interface SmartLifecycle extends Lifecycle, Phased {
default boolean isAutoStartup() {
return true;
}

default void stop(Runnable callback) {
stop();
callback.run();
}

default int getPhase() {
return DEFAULT_PHASE;
}
}

在Lifecycle的基础上实现了onRefresh和onClose接口。参见前面:Spring源码-ApplicationContext文章中finishRefresh中的代码片段。onRefresh会调用Lifecycle实现类的start()方法

1
2
3
4
5
6
7
// Initialize lifecycle processor for this context.
//初始化LifecycleProcessor
initLifecycleProcessor();

// Propagate refresh to lifecycle processor first.
//调用上面的LifecycleProcessor.onRefresh()
getLifecycleProcessor().onRefresh();
1
2
3
4
public interface LifecycleProcessor extends Lifecycle {  
void onRefresh();
void onClose();
}

调用流程

tbd