spring源码解析(六)

bean对象的初始化及销毁时,执行相关操作的几种方式。

package com.test;

import org.springframework.beans.factory.DisposableBean;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import javax.annotation.PreDestroy;

/**
 * @Description:  bean对象初始化/销毁的测试
 * @author: wanglei
 * @Date: 2024/1/10 15:04
 * @Version: 1.0
 */
public class TestInit {

    /**
     * 对象的初始和销毁时的三种方式:
     * 1、使用   @PostConstruct    @PreDestroy
     * 2、使用    @Bean(initMethod = "init",destroyMethod = "destory")
     * 3、bean对象的类实现InitializingBean, DisposableBean接口对应的方法。
     */

    @Configuration
    @ComponentScan
    static class MyConfig{

        //initMethod/destroyMethod的值表示,当前的bean在创建/销毁时执行的方法
        //注意:如果destroyMethod没有指定,那么会默认去找(shutdown或者close)方法执行
        @Bean(initMethod = "init",destroyMethod = "destory")
        public MyBean myBean(){
            return new MyBean();
        }
    }

    static class MyBean{
        public void init(){
            System.out.println("MyBean.init()");
        }

        public void destory(){
            System.out.println("MyBean.destory()");
        }
    }

    //初始化对象实现的方式2:实现InitializingBean,DisposableBean实现接口中对应的方法
    @Component
    static class MyBean2 implements InitializingBean, DisposableBean {

        //初始化时执行的方法
        @Override
        public void afterPropertiesSet() throws Exception {
            System.out.println("MyBean2.afterPropertiesSet()");
        }

        //对象销毁时,执行的方法
        @Override
        public void destroy() throws Exception {
            System.out.println("MyBean2.destroy()");
        }
    }

    public static void main(String[] args) {
        //容器在初始化时,会加载所有的bean对象至容器中
        AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(MyConfig.class);
        //注意只有在执行了close时,容器才会执行对bean对象的销毁方法
        context.close();
    }


}

你可能感兴趣的:(spring源码解析,spring,java,后端)