• 管理Spring生命周期的几种方式


    要介入spring的生命周期,即在spring容器启动后和容器销毁前进行定制化操作,有以下四种方法:

    1、实现Spring框架的InitializingBeanDisposableBean接口。

      容器为前者调用afterPropertiesSet()方法,为后者调用destroy()方法,以允许bean在初始化和销毁bean时执行某些操作。

    public class MyLifeCycle implements InitializingBean, DisposableBean {
        
        public void afterPropertiesSet() throws Exception {
            System.out.println("afterPropertiesSet 启动");
        }
    
        public void destroy() throws Exception {
            System.out.println("DisposableBean 停止");
        }
    }

    2、bean自定义初始化方法和销毁方法

    <bean id="MyLifeCycle" class="com.hzways.life.cycle.HelloLifeCycle" init-method="init3" destroy-method="destroy3"/>

    3、@PostConstruct和@PreDestroy注解,该方法在初始化bean时依赖注入操作之后被执行。

    public class MyLifeCycle {
    
        @PostConstruct
        private void init() {
            System.out.println("PostConstruct 启动");
        }
    
        @PreDestroy
        private void destroy() {
            System.out.println("PreDestroy 停止");
        }
    
    }

    按spring中bean的生命周期执行时机来看,以上三种方式的执行顺序如下:

    • 创建bean时
      1. @PostConstruct 注解方式 (依赖注入完成后,populateBean方法)
      2. InitializingBean 实现接口方式(初始化initializaBean方法中的自定义init方法之前)
      3. custom init() 自定义初始化方法方式
    • 销毁bean时
      1. @PreDestroy 注解方式
      2. DisposableBean  实现接口方式
      3. custom destroy() 自定义销毁方法方式

    4、实现LifeCycle 接口

    public interface Lifecycle {
        
        void start();
        
        void stop();
    
        boolean isRunning();
    
    }

      spring通过委托给生命中周期处理器 LifecycleProcessor 去执行 LifeCycle 接口的方法

    public interface LifecycleProcessor extends Lifecycle {
        /**
         * 响应Spring容器上下文 refresh
         */
        void onRefresh();
    
        /**
         * 响应Spring容器上下文 close
         */
        void onClose();
    }

      说明:常规的LifeCycle接口只是在容器上下文显式的调用start()/stop()方法时,才会去回调LifeCycle的实现类的start stop方法逻辑。并不意味着在上下文刷新时自动启动。如下:

    public static void main(String[] args) throws InterruptedException {
            ClassPathXmlApplicationContext applicationContext = new ClassPathXmlApplicationContext("classpath*:services.xml");
            applicationContext.start();
            applicationContext.close();
    }

      如果要实现自动调用,可以实现LifeCycle的子类 SmartLifecycle。

    public interface SmartLifecycle extends Lifecycle, Phased {
    
        /**
          * 如果该`Lifecycle`类所在的上下文在调用`refresh`时,希望能够自己自动进行回调,则返回`true`* ,
          * false的值表明组件打算通过显式的start()调用来启动,类似于普通的Lifecycle实现。
         */
        boolean isAutoStartup();
    
       
        void stop(Runnable callback);
    
    }

      它通过autoStartUp来控制是否自动调用,如果为true则自动调用,为false则跟普通的LifeCycle一样。

  • 相关阅读:
    人生苦短,Let's Go目录
    Python之路目录
    asyncio异步编程
    Golang实现集合(set)
    Python常用功能函数系列总结(四)之数据库操作
    Python常用功能函数系列总结(三)
    Python常用功能函数系列总结(二)
    Python爬取中国知网文献、参考文献、引证文献
    Python常用功能函数系列总结(一)
    Go语言系列之标准库ioutil
  • 原文地址:https://www.cnblogs.com/jing-yi/p/15343395.html
Copyright © 2020-2023  润新知