• spring中的Lifecycle


    spring中的Lifecycle

    Lifecycle介绍

    Lifecycle是spring中的生命循环接口,实现该接口的类将会可以启动,关闭。在AbstractApplicationContext通过ConfigurableApplicationContext接口中就实现了Lifecycle,当上下文调用start()函数时,就会去BeanFactory中找实现了Lifecycle接口的Bean,并调用该bean的start()函数。

    AbstractApplicationContext源码分析

    初始化LifecycleProcessor

    AbstractApplicationContext中有方法initLifecycleProcessor(),用来初始化生命周期执行器,用以执行容器中所有实现了Lifecycle接口的bean。

    /**
    	 * Initialize the LifecycleProcessor.
    	 * Uses DefaultLifecycleProcessor if none defined in the context.
    	 * @see org.springframework.context.support.DefaultLifecycleProcessor
    	 */
    protected void initLifecycleProcessor() {
        ConfigurableListableBeanFactory beanFactory = getBeanFactory();
        //参试在容器中获取LifecycleProcessor
        if (beanFactory.containsLocalBean(LIFECYCLE_PROCESSOR_BEAN_NAME)) {
            this.lifecycleProcessor =
                beanFactory.getBean(LIFECYCLE_PROCESSOR_BEAN_NAME, LifecycleProcessor.class);
            if (logger.isTraceEnabled()) {
                logger.trace("Using LifecycleProcessor [" + this.lifecycleProcessor + "]");
            }
        }
        else {
            //容器没有则使用DefaultLifecycleProcessor
            DefaultLifecycleProcessor defaultProcessor = new DefaultLifecycleProcessor();
            //设置BeanFactory,因为要对BeanFactory里面的Lifecycle bean调用start,stop
            defaultProcessor.setBeanFactory(beanFactory);
            this.lifecycleProcessor = defaultProcessor;
            //注册到容器中
            beanFactory.registerSingleton(LIFECYCLE_PROCESSOR_BEAN_NAME, this.lifecycleProcessor);
            if (logger.isTraceEnabled()) {
                logger.trace("No '" + LIFECYCLE_PROCESSOR_BEAN_NAME + "' bean, using " +
                             "[" + this.lifecycleProcessor.getClass().getSimpleName() + "]");
            }
        }
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29

    start()和stop()

    AbstractApplicationContext中的start()和stop()方法用来启动生命周期。通过LifecycleProcessor来去启动BeanFactory中的实现了Lifecycle接口的bean。

    //---------------------------------------------------------------------
    // Implementation of Lifecycle interface
    //---------------------------------------------------------------------
    
    @Override
    public void start() {
        getLifecycleProcessor().start();
        publishEvent(new ContextStartedEvent(this));
    }
    
    @Override
    public void stop() {
        getLifecycleProcessor().stop();
        publishEvent(new ContextStoppedEvent(this));
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15

    DefaultLifecycleProcessor源码分析

    start()和startBeans()

    DefaultLifecycleProcessor通过从BeanFactory中获取LifecycleBean,并调用它们的start()方法

    @Override
    public void start() {
        startBeans(false);
        this.running = true;
    }
    
    // Internal helpers
    
    private void startBeans(boolean autoStartupOnly) {
        //这里是从BeanFactory中获取所有LifecycleBean
        Map<String, Lifecycle> lifecycleBeans = getLifecycleBeans();
        Map<Integer, LifecycleGroup> phases = new HashMap<>();
        lifecycleBeans.forEach((beanName, bean) -> {
            if (!autoStartupOnly || (bean instanceof SmartLifecycle && ((SmartLifecycle) bean).isAutoStartup())) {
                int phase = getPhase(bean);
                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) {
                //最后会调用该bean的start()方法
                phases.get(key).start();
            }
        }
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32

    Lifecycle Bean使用示例

    MyLifecycleBean

    /**
     * @author liangwy 
     * @since 2022-5-17
     */
    public class MyLifecycleBean implements Lifecycle {
        
        private Boolean flag = false;
        
        @Override
        public void start() {
            this.flag = true;
            System.out.println("启动MyLifecycleBean");
        }
    
        @Override
        public void stop() {
            this.flag = false;
            System.out.println("关闭MyLifecycleBean");
        }
    
        @Override
        public boolean isRunning() {
            return flag;
        }
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25

    测试

    public static void main(String[] args) {
    
        AnnotationConfigApplicationContext applicationContext = runAnnotationConfigApplicationContext();
        applicationContext.start();
        MyLifecycleBean myLifecycleBean = applicationContext.getBean("myLifecycleBean", MyLifecycleBean.class);
        System.out.println(myLifecycleBean.isRunning());
        applicationContext.stop();
        System.out.println(myLifecycleBean.isRunning());
    }
    
    /**
         * 注解配置方式创建上下文
         * @return
         */
    public static AnnotationConfigApplicationContext runAnnotationConfigApplicationContext(){
        AnnotationConfigApplicationContext applicationContext = new AnnotationConfigApplicationContext(ApplicationMain.class);
        applicationContext.getBeanFactory().registerCustomEditor(Date.class,TestPropertyEditorSupport.class);
        return applicationContext;
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19

    结果打印

    启动MyLifecycleBean
    true
    关闭MyLifecycleBean
    false

  • 相关阅读:
    c++的引用和指针
    第二章——古典密码学及算法实现
    一种基于Frost滤波算法的散斑噪声抑制的仿真与实验分析
    ceph 数据恢复和回填速度 重建osd 加快数据恢复
    CSS 标准流 浮动 Flex布局
    Swift data范围截取问题
    【附源码】计算机毕业设计JAVA互联网保险网站
    uniapp 微信小程序根据后端返回的文件链接打开并保存到手机文件夹中【支持doc、docx、txt、xlsx等类型的文件】
    Linux_/proc目录_查看处理器的信息/proc/cpuinfo
    二、Java 开发环境配置(Windows11系统为例)
  • 原文地址:https://blog.csdn.net/qq_43203949/article/details/125454741