Tomcat的组件都会实现一个Lifecycle接口,以方便组件的生命周期的统一管理
interface Lifecycle
组件生命周期中主要的几个方法
增加监听器,事件委托机制
public void addLifecycleListener(LifecycleListener listener); public void removeLifecycleListener(LifecycleListener listener); 组件初始化 public void init() throws LifecycleException; public void start() throws LifecycleException; 组件停止,当stop()方法执行完后会自动调用destroy()方法销毁组件 public void stop() throws LifecycleException; public void destroy() throws LifecycleException; public LifecycleState getState();
事件有:
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"; public static final String BEFORE_START_EVENT = "before_start"; public static final String AFTER_START_EVENT = "after_start"; public static final String STOP_EVENT = "stop"; public static final String BEFORE_STOP_EVENT = "before_stop"; public static final String AFTER_STOP_EVENT = "after_stop"; public static final String AFTER_DESTROY_EVENT = "after_destroy"; public static final String BEFORE_DESTROY_EVENT = "before_destroy"; public static final String PERIODIC_EVENT = "periodic"; //定期 public static final String CONFIGURE_START_EVENT = "configure_start"; public static final String CONFIGURE_STOP_EVENT = "configure_stop";
在tomcat启动过程中用到的几个组件,如StandardServer,StandardService,StandardEngine,StandardThreadExecutor,Connector等组件都间接实现了Lifecycle接口
如StandardServer
==>public final class StandardServer extends LifecycleMBeanBase implements Server
继承LifecycleMBeanBase
==>实现Server接口----不讨论
===>
public abstract class LifecycleMBeanBase extends LifecycleBase
implements JmxEnabled
===>public abstract class LifecycleBase implements Lifecycle
当调用StandardServer.init()方法时会调用Lifecycle.init()方法,
又因Lifecycle是接口,所以调用LifecycleBase这个接口的实现类LifecycleBase.init()
这个方法内部调用的LifecycleBase.initInternal()
在LifecycleBase中定义如下,就是一个抽象方法。需要继承这个类的所有组件实现这个方法。
protected abstract void initInternal() throws LifecycleException;
==》在LifecycleBase的子类中LifecycleMBeanBase中重写的这个initInternal()
进行组件注册到MBeanServer组件管理服务器中,这里是所有组件进行初始化动作时的操作,最后还是要到StandardServer的initInternal()方法具体实现。
@Override protected void initInternal() throws LifecycleException { // If oname is not null then registration has already happened via // preRegister(). if (oname == null) { mserver = Registry.getRegistry(null, null).getMBeanServer(); oname = register(this, getObjectNameKeyProperties()); } }
==》最后到StandardServer.initInternal()
上面的流程化简下:
StandardServer.init() =>Lifecycle.init() =>LifecycleBase.init() =>LifecycleBase.initInternal() =>LifecycleMBeanBase.initInternal() =>StandardServer.initInternal()
StandardServer.init()最终调用的是StandardServer.initInternal()
同理,由上面的过程可以知道我们调用组件的start(),stop(),destroy()方法时最后调用的是组件的
startInternal(),stopInternal(),destroyInternal()方法。
也不清楚这是什么设计模式,当感觉这个组件生命周期管理方法值得学习