《读spring源码》15 Bean的生命周期简单探索(单实例)

之前的版本中 bean 是可以在xml文件中 配置bean的初始化和销毁的method

    <bean id = "person" class="com.enjoy.cap1.Person" init-method="" destroy-method="">
        <property name="name" value="wyl"></property>
        <property name="age" value="19"></property>
    </bean>

接下来自己模拟一个创建–》 初始化 --》销毁的流程

package com.enjoy.cap7;

public class Bike {
    public Bike(){
        System.out.println("Bike constructor ………………");
    }
    public void init(){
        System.out.println("Bike init ……………………");
    }
    public void destory(){
        System.out.println("Bike destory…………………");
    }

}

package com.enjoy.cap7;


import com.enjoy.cap1.Person;
import com.enjoy.cap6.*;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Import;

@Configuration
@Import(value = {Dog.class,Cat.class,TTTTImportSelector.class,TTTImportBeanDefinitionRegistrar.class})
public class MainConfig {

    @Bean("person")
    public Person zhangsan(){
        System.out.println("给我们的容器中添加张三");
        return new Person("张三",22);
    }
    @Bean(initMethod = "init",destroyMethod = "destory")
    public Bike bike(){
        return new Bike();
    }


}

package test;

import com.enjoy.cap7.MainConfig;
import org.junit.jupiter.api.Test;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;

/**
 * FactoryBean 和 BeanFactorty 有什么区别?
 *
 * FactoryBean :可以把我们的JAVA实例通过FactoryBean注入到容器中
 *
 * BeanFactorty:从我们的容器中获取实例化后的bean
 *
 */
public class MainTEwst7 {

    @Test
    public void sss(){
        AnnotationConfigApplicationContext annotationConfigApplicationContext = new AnnotationConfigApplicationContext(MainConfig.class);
        System.out.println("容器起用完成");

    }
}

在这里插入图片描述
在默认情况下spring创建bean是单例模式,单例模式在创建容器的同事加入bean实例。
如上打印结果我们可以到打印出了 bean的新建 初始化的时候的打印日志

当我们再test用例里面加入如下一句话 就是关闭容器的时候 :

        annotationConfigApplicationContext.close();

打印日志如下:
在这里插入图片描述
我们可以看到日志中打印了destory的执行日志(当然这只是一个演示)

那么我们看一下close方法
在这里插入图片描述

在这里插入图片描述
在这里插入图片描述
销毁缓存中所有的单例的bean
在这里插入图片描述
在这里插入图片描述

发布了434 篇原创文章 · 获赞 58 · 访问量 31万+

猜你喜欢

转载自blog.csdn.net/ppwwp/article/details/103332353
今日推荐