Spring中的Lifecycle接口使用与源码分析

 更新时间:2023年05月12日 09:00:47   作者:morris131  
这篇文章主要介绍了Spring中的Lifecycle接口使用与源码分析,LifeCycle接口定义了Spring容器的生命周期,任何被Spring管理的对象都可以实现该接口,需要的朋友可以参考下

LifeCycle接口定义了Spring容器的生命周期,任何被Spring管理的对象都可以实现该接口。当Spring容器本身启动和停止时,会回调LifeCycle接口中定义的方法。

Lifecycle接口的声明

org.springframework.context.Lifecycle

public interface Lifecycle {
	    /**
     * 启动当前组件,如果组件已经在运行,不应该抛出异常,这样将开始信号传播到应用的所有组件中去。
     */
	void start();
	    /**
     * 通常以同步方式停止该组件,当该方法执行完成后,该组件会被完全停止。当需要异步停止行为时,考虑实现SmartLifecycle和它的 stop(Runnable) 方法变体。 
	 注意,此停止通知在销毁前不能保证到达:
    在常规关闭时,{@code Lifecycle} bean将首先收到一个停止通知,然后才传播常规销毁回调;
    在上下文的生命周期内的刷新或中止时,只调用销毁方法
    对于容器,这将把停止信号传播到应用的所有组件
     */
	void stop();
	    /**
      *  检查此组件是否正在运行。
      *  1. 只有该方法返回false时,start方法才会被执行。
      *  2. 只有该方法返回true时,stop(Runnable callback)或stop()方法才会被执行。
      */
	boolean isRunning();
}

Lifecycle的使用

自定义一个Lifecycle需要实现Lifecycle接口:

package com.morris.spring.demo.lifecycle;
import org.springframework.context.Lifecycle;
/**
 * 自定义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;
	/**
      * 如果该`Lifecycle`类所在的上下文在调用`refresh`时,希望能够自己自动进行回调,则返回`true`* ,
      * false的值表明组件打算通过显式的start()调用来启动,类似于普通的Lifecycle实现。
     */
	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;
/**
 * 自定义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;
/**
 * 演示SmartLifecycle
 */
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
	/**
		 * @see DefaultLifecycleProcessor#start()
		 */
	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接口内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!

相关文章

最新评论