LifeCycle接口定义了Spring容器的生命周期,任何被Spring管理的对象都可以实现该接口。当Spring容器本身启动和停止时,会回调LifeCycle接口中定义的方法。
Lifecycle接口的声明
org.springframework.context.Lifecycle
public interface Lifecycle {
void start();
void stop();
boolean isRunning();
}
Lifecycle的使用
自定义一个Lifecycle需要实现Lifecycle接口:
package com.morris.spring.demo.lifecycle;
import org.springframework.context.Lifecycle;
public class MyLifecycle implements Lifecycle {
private boolean isRunning;
@Override
public void start() {
System.out.println("MyLifecycle start");
isRunning = true;
}
@Override
public void stop() {
System.out.println("MyLifecycle stop");
isRunning = false;
}
@Override
public boolean isRunning() {
return isRunning;
}
}
测试类:
public class LifecycleDemo {
public static void main(String[] args) {
AnnotationConfigApplicationContext applicationContext = new AnnotationConfigApplicationContext();
applicationContext.register(MyLifecycle.class);
applicationContext.refresh();
}
}
启动main()方法后发现并没有调用MyLifecycle的start()和stop()方法。
把测试类改为如下,主动调用applicationContext容器的start()和stop()方法:
public class LifecycleDemo {
public static void main(String[] args) {
AnnotationConfigApplicationContext applicationContext = new AnnotationConfigApplicationContext();
applicationContext.register(MyLifecycle.class);
applicationContext.refresh();
applicationContext.start();
applicationContext.stop();
}
}
运行结果如下:
DEBUG main DefaultLifecycleProcessor:356 - Starting beans in phase 0
MyLifecycle start
DEBUG main DefaultLifecycleProcessor:188 - Successfully started bean 'myLifecycle'
DEBUG main DefaultLifecycleProcessor:369 - Stopping beans in phase 0
MyLifecycle stop
DEBUG main DefaultLifecycleProcessor:253 - Successfully stopped bean 'myLifecycle'
这时我们看到Spring容器回调了Lifecycle生命周期的方法。
SmartLifecycle接口的声明
常规的LifeCycle接口只能在容器上下文显式的调用start()或stop()方法时,才会去回调LifeCycle的实现类的start()或stop()方法逻辑,并不意味着在容器上下文刷新时自动回调。
org.springframework.context.SmartLifecycle
public interface SmartLifecycle extends Lifecycle, Phased {
int DEFAULT_PHASE = Integer.MAX_VALUE;
default boolean isAutoStartup() {
return true;
}
default void stop(Runnable callback) {
stop();
callback.run();
}
@Override
default int getPhase() {
return DEFAULT_PHASE;
}
}
SmartLifecycle的使用
自定义SmartLifecycle需要实现SmartLifecycle接口:
package com.morris.spring.demo.lifecycle;
import org.springframework.context.SmartLifecycle;
public class MySmartLifecycle implements SmartLifecycle {
private boolean isRunning;
@Override
public void start() {
System.out.println("MyLifecycle start");
isRunning = true;
}
@Override
public void stop() {
System.out.println("MyLifecycle stop");
isRunning = false;
}
@Override
public boolean isRunning() {
return isRunning;
}
}
测试类:
package com.morris.spring.demo.lifecycle;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
public class SmartLifecycleDemo {
public static void main(String[] args) {
AnnotationConfigApplicationContext applicationContext = new AnnotationConfigApplicationContext();
applicationContext.register(MySmartLifecycle.class);
applicationContext.refresh();
}
}
运行结果如下:
DEBUG main DefaultListableBeanFactory:228 - Creating shared instance of singleton bean 'mySmartLifecycle'
DEBUG main DefaultLifecycleProcessor:357 - Starting beans in phase 2147483647
MyLifecycle start
DEBUG main DefaultLifecycleProcessor:189 - Successfully started bean 'mySmartLifecycle'
容器中多个实现了Lifecycle的类如果希望有顺序的进行回调时,那么启动和关闭调用的顺序可能很重要。如果任何两个对象之间存在依赖关系,那么依赖方将在依赖后开始,在依赖前停止。然而,有时直接依赖关系是未知的。您可能只知道某个类型的对象应该在另一个类型的对象之前开始。在这些情况下,SmartLifecycle接口定义了另一个选项,即在其超接口上定义的getPhase()方法。
当开始时,getPhase()返回值最小的对象先开始,当停止时,遵循相反的顺序。因此,实现SmartLifecycle的对象及其getPhase()方法返回Integer.MIN_VALUE将在第一个开始和最后一个停止。相反,MAX_VALUE将指示对象应该在最后启动并首先停止。
源码解读
Lifecycle的调用时机
Lifecycle中的方法只有在主动调用容器的start()和stop()方法时才会触发,所以直接看容器的start()或stop()方法即可。
org.springframework.context.support.AbstractApplicationContext#start
public void start() {
// 获取DefaultLifecycleProcessor
getLifecycleProcessor().start();
publishEvent(new ContextStartedEvent(this));
}
org.springframework.context.support.DefaultLifecycleProcessor#start
public void start() {
startBeans(false);
this.running = true;
}
最后会调用DefaultLifecycleProcessor的startBeans()方法。
SmartLifecycle的调用时机
SmartLifecycle的调用时机发生在容器refresh()时。
org.springframework.context.support.AbstractApplicationContext#finishRefresh
protected void finishRefresh() {
// Clear context-level resource caches (such as ASM metadata from scanning).
clearResourceCaches();
// Initialize lifecycle processor for this context.
// 注入DefaultLifecycleProcessor
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);
}
DefaultLifecycleProcessor的创建并调用onRefresh()方法。
org.springframework.context.support.DefaultLifecycleProcessor#onRefresh
public void onRefresh() {
startBeans(true);
this.running = true;
}
通用最后会调用DefaultLifecycleProcessor的startBeans()方法,只不过参数传入true。
DefaultLifecycleProcessor.startBeans()
private void startBeans(boolean autoStartupOnly) {
// 拿到容器中所有的Lifecycle
Map<String, Lifecycle> lifecycleBeans = getLifecycleBeans();
Map<Integer, LifecycleGroup> phases = new HashMap<>();
lifecycleBeans.forEach((beanName, bean) -> {
if (!autoStartupOnly || (bean instanceof SmartLifecycle && ((SmartLifecycle) bean).isAutoStartup())) {
// autoStartupOnly=false,表示调用的Lifecycle
// autoStartupOnly=true,表示调用的SmartLifecycle
int phase = getPhase(bean);
// 根据phase进行分组
LifecycleGroup group = phases.get(phase);
if (group == null) {
group = new LifecycleGroup(phase, this.timeoutPerShutdownPhase, lifecycleBeans, autoStartupOnly);
phases.put(phase, group);
}
group.add(beanName, bean);
}
});
if (!phases.isEmpty()) {
List<Integer> keys = new ArrayList<>(phases.keySet());
Collections.sort(keys);
for (Integer key : keys) {
// 调用start()
phases.get(key).start();
}
}
}
到此这篇关于Spring中的Lifecycle接口使用与源码分析的文章就介绍到这了,更多相关Spring中的Lifecycle接口内容请搜索编程网以前的文章或继续浏览下面的相关文章希望大家以后多多支持编程网!