Bean对象的生命周期

Posted by zjhChester on September 29, 2019

bean对象的生命周期

1、单例对象:

出生:

当文件创建时对象出生(刚解析完配置文件)ApplicationContext

活着:

只要容器还在,对象一直活着

死亡:

容器销毁,对象销毁

总结:

单例对象生命周期与容器相同

测试:

第一步:

<!-- 指定bean对象销毁和初始化的方法 -->
<!-- scope="singleton" 单例模式-->
 <bean scope="singleton" id="Service" class="com.tfs.service.impl.ServiceImpl" init-method="init" destroy-method="destroy">

第二步:

//编写对应bean对象的init destroy方法
public void init() {
        System.out.println("对象初始化了");
    }

    public void destroy() {
        System.out.println("对象销毁了");
    }

第三步:

编写测试类:

 //指定容器类型为类类型,避免多态性导致无法关闭容器
        ClassPathXmlApplicationContext ac = new ClassPathXmlApplicationContext("beans.xml");
        Service service = ac.getBean("Service",Service.class);
        service.say();
        //手动销毁
        ac.close();

结果:

1569730513921

2、多例对象:

<!--scope="prototype"多例对象 -->
<bean scope="prototype" id="Service" class="com.tfs.service.impl.ServiceImpl" init-method="init" destroy-method="destroy">

出生:

当我们使用对象时spring框架才会创建

活着:

对象只要是在使用过程中就活着

死亡:

当对象长时间不用,且没有别的对象引用时。由java的垃圾回收器GC回收