最近看到一个讲解文章附上链接:https://juejin.cn/post/7075168883744718856
Bean对象的生命周期:
<!-- bean的生命周期:
单例对象: 将创建的bean放入容器
出生:容器创建,对象出生 配置文件加载完毕后,会立即创建bean对象,并存放到IOC容器中
活着:只要容器在,对象就一直活着
死亡:容器销毁,对象消亡
特点:生命周期与容器相同 -->
<!-- 单例对象: init-method: 初始化方法 destroy-method: 销毁时调用的方法 -->
<!--<bean scope="singleton" init-method="initMethod" destroy-method="destoryMethod"
id="AccountService5" class="com.village.service.impl.AccountServiceImpl"></bean>
-->
<!--
多实例bean的生命周期:
创建时机:
从IOC容器中获取对象时
销毁时机:
等待GC回收
-->
<!--
多例对象:
出生:每次使用时创建
活着:在使用过程中
死亡:使用完成之后,等待垃圾回收器回收。
多实例bean对象的生命周期
scope的值必须为: prototype
-->
<bean scope="prototype" init-method="initMethod" destroy-method="destoryMethod"
id="AccountService6" class="com.village.service.impl.AccountServiceImpl"></bean>
package com.village.web;
import com.village.service.AccountService;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class BeanLifeClient {
public static void main(String[] args) {
/*ApplicationContext ac = new ClassPathXmlApplicationContext("applicationContext.xml");
AccountService service = ac.getBean("AccountService5", AccountService.class);
service.save();;
// 关闭IOC容器
((ClassPathXmlApplicationContext) ac).close();*/
ApplicationContext ac = new ClassPathXmlApplicationContext("applicationContext.xml");
AccountService service = ac.getBean("AccountService6", AccountService.class);
service.save();;
// 关闭IOC容器
((ClassPathXmlApplicationContext) ac).close();
}
}