Spring容器生命周期管理:SmartLifecycle

前言:

    笔者之前在项目中倒也没有关注过Spring容器的生命周期管理(大家注意下:之前一篇博客介绍的是Spring中Bean的生命周期管理,与目前要介绍的Spring容器的生命周期管理倒还是千差万别的,千万不要混淆了)。

    Spring容器,我们常用的就是ApplicationContext,容器本身是存放Bean和Bean之间的依赖关系的,那么容器的生命周期是什么概念呢?

    我们可以尝试从Bean的生命周期来推敲,Spring容器本身也是一个对象,既然是对象,那肯定也有创建和销毁,类似于Bean的init和destroy,只不过容器不叫做创建和销毁,而是start()和stop()

    如果我们想在容器初始化完所有的Bean之后做点什么,或者想在容器关闭之前做点记录,应该怎么操作呢?

    这个就是本文要关注的SmartLifeCycle

1.SmartLifeCycle的介绍

    SmartLifeCycle是一个接口,具体继承关系如下:

    方法介绍如下(来自于https://blog.csdn.net/boling_cavalry/article/details/82051356  ):

2.SmartLifeCycle的简单使用

    我们先简单使用下SmartLifeCycle,然后再结合结果来分析

    代码来自于https://blog.csdn.net/catoop/article/details/71274561  :

public class SmartLifeCycleDemo implements SmartLifecycle {

    private boolean isRunning = false;

    /**
     * 1. 我们主要在该方法中启动任务或者其他异步服务,比如开启MQ接收消息<br/>
     * 2. 当上下文被刷新(所有对象已被实例化和初始化之后)时,将调用该方法,默认生命周期处理器将检查每个SmartLifecycle对象的isAutoStartup()方法返回的布尔值。
     * 如果为“true”,则该方法会被调用,而不是等待显式调用自己的start()方法。
     */
    @Override
    public void start() {
        System.out.println("start");

        // 执行完其他业务后,可以修改 isRunning = true
        isRunning = true;
    }

    /**
     * 如果工程中有多个实现接口SmartLifecycle的类,则这些类的start的执行顺序按getPhase方法返回值从小到大执行。<br/>
     * 例如:1比2先执行,-1比0先执行。 stop方法的执行顺序则相反,getPhase返回值较大类的stop方法先被调用,小的后被调用。
     */
    @Override
    public int getPhase() {
        // 默认为0
        return 0;
    }

    /**
     * 根据该方法的返回值决定是否执行start方法。<br/>
     * 返回true时start方法会被自动执行,返回false则不会。
     */
    @Override
    public boolean isAutoStartup() {
        // 默认为false
        return true;
    }

    /**
     * 1. 只有该方法返回false时,start方法才会被执行。<br/>
     * 2. 只有该方法返回true时,stop(Runnable callback)或stop()方法才会被执行。
     */
    @Override
    public boolean isRunning() {
        // 默认返回false
        return isRunning;
    }

    /**
     * SmartLifecycle子类的才有的方法,当isRunning方法返回true时,该方法才会被调用。
     */
    @Override
    public void stop(Runnable callback) {
        System.out.println("stop(Runnable)");

        // 如果你让isRunning返回true,需要执行stop这个方法,那么就不要忘记调用callback.run()。
        // 否则在你程序退出时,Spring的DefaultLifecycleProcessor会认为你这个TestSmartLifecycle没有stop完成,程序会一直卡着结束不了,等待一定时间(默认超时时间30秒)后才会自动结束。
        // PS:如果你想修改这个默认超时时间,可以按下面思路做,当然下面代码是springmvc配置文件形式的参考,在SpringBoot中自然不是配置xml来完成,这里只是提供一种思路。
        // <bean id="lifecycleProcessor" class="org.springframework.context.support.DefaultLifecycleProcessor">
        //      <!-- timeout value in milliseconds -->
        //      <property name="timeoutPerShutdownPhase" value="10000"/>
        // </bean>
        callback.run();

        isRunning = false;
    }

    /**
     * 接口Lifecycle的子类的方法,只有非SmartLifecycle的子类才会执行该方法。<br/>
     * 1. 该方法只对直接实现接口Lifecycle的类才起作用,对实现SmartLifecycle接口的类无效。<br/>
     * 2. 方法stop()和方法stop(Runnable callback)的区别只在于,后者是SmartLifecycle子类的专属。
     */
    @Override
    public void stop() {
        System.out.println("stop");

        isRunning = false;
    }

}

    1)测试代码及结果

// 1.注意需要把该bean注入到容器中,在beans.xml中添加该bean
<bean id="smartLifeCycle" class="lifecycle.SmartLifeCycleDemo"/>

// 2.测试类代码
@Test
public void testXml(){
        ClassPathXmlApplicationContext applicationContext = new ClassPathXmlApplicationContext("beans.xml");
        applicationContext.close();
}

// res
...
10:12:04,875 DEBUG main support.DefaultListableBeanFactory:537 - Eagerly caching bean 'bookEnglish' to allow for resolving potential circular references
10:12:04,875 DEBUG main support.DefaultListableBeanFactory:483 - Finished creating instance of bean 'bookEnglish'
10:12:04,875 DEBUG main support.DefaultListableBeanFactory:251 - Returning cached instance of singleton bean 'org.springframework.context.event.internalEventListenerFactory'
10:12:04,930 DEBUG main support.DefaultListableBeanFactory:251 - Returning cached instance of singleton bean 'smartLifeCycle'
10:12:04,930 DEBUG main support.DefaultListableBeanFactory:251 - Returning cached instance of singleton bean 'lifecycleProcessor'
    // 以上是创建bean的日志
10:12:04,930  INFO main support.DefaultLifecycleProcessor:345 - Starting beans in phase 0
start // 在这里执行LifeCycleDemo的start()方法
10:12:04,945  INFO main support.ClassPathXmlApplicationContext:985 - Closing org.springframework.context.support.ClassPathXmlApplicationContext@6ad5c04e: startup date [Sat May 04 10:12:04 GMT+08:00 2019]; root of context hierarchy
10:12:04,945 DEBUG main support.DefaultListableBeanFactory:251 - Returning cached instance of singleton bean 'smartLifeCycle'
10:12:04,945 DEBUG main support.DefaultListableBeanFactory:251 - Returning cached instance of singleton bean 'lifecycleProcessor'
10:12:04,945  INFO main support.DefaultLifecycleProcessor:360 - Stopping beans in phase 0
stop(Runnable) // 容器执行close方法后,调用LifeCycleDemo.stop()方法

    总结:LifeCycleDemo.start()方法确实是在所有Bean都加载完成之后才执行的。

    通过这个特性,我们可以完成一些需要启动执行的任务。

    比如网友分享的一个示例:是关于Eureka的

    示例来自于:https://blog.csdn.net/zouhuixing/article/details/80304141  

@Configuration
@CommonsLog
public class EurekaServerInitializerConfiguration
		implements ServletContextAware, SmartLifecycle, Ordered {
 
	@Override
	public void start() {
		new Thread(new Runnable() {
			@Override
			public void run() {
				try {
					//TODO: is this class even needed now?
					eurekaServerBootstrap.contextInitialized(EurekaServerInitializerConfiguration.this.servletContext);
					log.info("Started Eureka Server");
 
					publish(new EurekaRegistryAvailableEvent(getEurekaServerConfig()));
					EurekaServerInitializerConfiguration.this.running = true;
					publish(new EurekaServerStartedEvent(getEurekaServerConfig()));
				}
				catch (Exception ex) {
					// Help!
					log.error("Could not initialize Eureka servlet context", ex);
				}
			}
		}).start();
	}
 
}

    Spring在Bean加载完成之后启动Eureka服务器,实现服务注册与发现

总结:

    我们可以通过实现SmartLifeCycle接口,实现其start() stop()方法来完成一些需要启动加载,关闭前执行的动作。

参考:

https://docs.spring.io/spring/docs/4.3.23.RELEASE/spring-framework-reference/htmlsingle/ 

代码地址:https://github.com/kldwz/springstudy  

发布了122 篇原创文章 · 获赞 119 · 访问量 12万+

猜你喜欢

转载自blog.csdn.net/qq_26323323/article/details/89814304