工厂创建的对象的生命周期
Spring学习笔记 周芋杉2021/5/21
1.工厂创建对象的阶段
在创建对象时同时会优先调用无参构造方法
工厂在何时创建对象
1.bean标签内指定scope=“singleton”
Spring将会在工厂创建时创建对象
例如
在xml文件中
<bean id="product" class="org.LifeCricle.LifeTestObject"scope="singleton"/>
实现类中
public class LifeTestObject {
public LifeTestObject(){
//构造方法
System.out.println("LifeTestObject has product");
}
//自定义的方法在创建对象时打印出语句
public void MyIntMethod(){
System.out.println("LifeTestObject.MyIntMethod");
}
}
那只需要创建工厂即可创建对象
ApplicationContext context = new ClassPathXmlApplicationContext("/ApplicationContext.xml");
结果为
2.bean标签内指定scope=“prototype”
对象将在获取对象时候创建
例如
在XML中
<bean id="product" class="org.LifeCricle.LifeTestObject"scope="prototype"/>
实现类依然如上
我们只创建工厂发现并没有打印出语句,所以对象并没有被创建
ApplicationContext context = new ClassPathXmlApplicationContext("/ApplicationContext.xml");
//LifeTestObject lifeTestObject= (LifeTestObject) context.getBean("product");
接着取消注释发现对象被创建了
2初始化阶段
Spring创建完成对象之后,才会调用对象的初始化方法。
开发步骤
- 实现InitializingBean接口,重写afterPropertiesSet()
- 提供普通方法
1.实现InitializingBean接口
public class IntMethodTest implements InitializingBean {
//构造方法
public IntMethodTest(){
System.out.println("IntMethodTest.IntMethodTest");
}
// 初始化普通方法
public void intmethod(){
System.out.println("IntMethodTest.intmethod");
}
//初始化方法
@Override
public void afterPropertiesSet() throws Exception {
System.out.println("IntMethodTest.afterPropertiesSet");
}
}
2在XML中配置init-method
<bean id="intmethod" class="org.LifeCricle.IntMethodTest" init-method="intmethod" scope="prototype"/>
注意:如果不使用init-method则不会初始化普通方法
运行结果
细节:
我们可以看到优先度构造方法>初始化方法>普通方法
注入发生在初始化前面
应用场景:IO 数据库 网络配置
3.销毁阶段
Spring 销毁对象发生在工厂关闭时
在关闭工厂我们需要使用Application的父接口ClassPathXmlApplicationContext
例如
1.在实现类继续实现DisposableBean接口
public class IntMethodTest implements InitializingBean, DisposableBean {
public IntMethodTest(){
System.out.println("IntMethodTest.IntMethodTest");
}
public void intmethod(){
System.out.println("IntMethodTest.intmethod");
}
@Override
public void afterPropertiesSet() throws Exception {
System.out.println("IntMethodTest.afterPropertiesSet");
}
//工厂关闭时候的操作
@Override
public void destroy() throws Exception {
System.out.println("IntMethodTest.destroy");
}
//自定义关闭操作
public void Mydestory(){
System.out.println("IntMethodTest.Mydestory");
}
}
2.在XML中指定销毁方法destroy-method
为了验证,所以把对象设置在创建工厂时候创建
<bean id="intmethod" class="org.LifeCricle.IntMethodTest" init-method="intmethod" destroy-method="Mydestory" scope="singleton"/>
3.销毁操作
ClassPathXmlApplicationContext context=new ClassPathXmlApplicationContext("/ApplicationContext.xml");
context.close();
结果如下
使用场景:资源释放,IO关闭,数据库连接关闭