三、Tomcat源码分析-启动分析(一) Lifecycle
Lifecycle在其他框架中也很常见,比如spring,它常用于具有生命周期的组件,由Lifecycle控制组件的初始化、启动、销毁等动作,方便应用程序获取、释放某些资源,或者是触发某些特定的事件。Tomcat也是如此,在学习整个启动流程之前,我们先行了解下Lifecycle的实现机制,便于理解整个流程。
Lifecycle
Lifecycle接口是一个公用的接口,定义了组件生命周期的一些方法,用于启动、停止Catalina组件。它是一个非常重要的接口,组件的生命周期包括:init、start、stop、destory,以及各种事件的常量、操作LifecycleListener的API,典型的观察者模式
public interface Lifecycle {
// ----------------------- 定义各种EVENT事件 -----------------------
public static final String BEFORE_INIT_EVENT = "before_init";
public static final String AFTER_INIT_EVENT = "after_init";
public static final String START_EVENT = "start";
// 省略事件常量定义……
/**
* 注册一个LifecycleListener
*/
public void addLifecycleListener(LifecycleListener listener);
/**
* 获取所有注册的LifecycleListener
*/
public LifecycleListener[] findLifecycleListeners();
/**
* 移除指定的LifecycleListener
*/
public void removeLifecycleListener(LifecycleListener listener);
/**
* 组件被实例化之后,调用该方法完成初始化工作,发会出以下事件
* <ol>
* <li>INIT_EVENT: On the successful completion of component initialization.</li>
* </ol>
* @exception LifecycleException if this component detects a fatal error
* that prevents this component from being used
*/
public void init() throws LifecycleException;
/**
* 在组件投入使用之前调用该方法,先后会发出以下事件:BEFORE_START_EVENT、START_EVENT、AFTER_START_EVENT
* @exception LifecycleException if this component detects a fatal error
* that prevents this component from being used
*/
public void start() throws LifecycleException;
/**
* 使组件停止工作
*/
public void stop() throws LifecycleException;
/**
* 销毁组件时被调用
*/
public void destroy() throws LifecycleException;
/**
* Obtain the current state of the source component.
*/
public LifecycleState getState();
/**
* 获取state的文字说明
*/
public String getStateName();
/**
* Marker interface used to indicate that the instance should only be used
* once. Calling {@linkstop()} on an instance that supports this interface
* will automatically call {@linkdestroy()} after {@linkstop()}
* completes.
*/
public interface SingleUse {
}