一、spring对象生命周期
首先创建一个UserInfo类,其中包含属性name,无参构造方法,静态与非静态构造方法,get和set方法,init和destroy方法,并且每一个方法都有相应的输出:
package club.affengkuang.vo;
public class UserInfo {
private String name;
public UserInfo() {
System.out.println("构造方法");
}
{
System.out.println("非静态代码块");
}
static {
System.out.println("静态代码块");
}
public String getName() {
System.out.println("get方法");
return name;
}
public void setName(String name) {
System.out.println("set方法");
this.name = name;
}
public void init() {
System.out.println("init");
}
public void destroy() {
System.out.println("destroy");
}
}
然后将该类添加到application.xml中,并调用set方法给属性name赋值,设置init-method和destroy-method值为init()和destroy()方法,这两个属性的意思分别是对象被创建时调用init()方法,被销毁时调用destroy()方法:
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">
<bean id="userInfo" class="club.affengkuang.vo.UserInfo" lazy-init="true" init-method="init" destroy-method="destroy">
<property name="name" value="Tom"></property>
</bean>
</beans>
然后在测试类中创建IOC容器,并从中获取一个UserInfo对象,这时spring对象的生命周期就在控制台上一览无遗了:
package club.affengkuang.test;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class Test {
public static void main(String[] args) {
ClassPathXmlApplicationContext applicationContext = new ClassPathXmlApplicationContext("application.xml");
Object object = applicationContext.getBean("userInfo");
System.out.println(object);
applicationContext.close();
}
}
当从IOC容器中获取UserInfo对象时,类似于java中对象的初始化过程:
先调用UserInfo类中的静态与非静态代码块(且先执行静态后执行非静态),然后调用UserInfo类中的构造方法,再调用set方法为name赋值,最后等对象创建完毕了再执行init()方法,这就是对象创建的全过程;
而destroy()方法执行的时间是当IOC容器被关闭时,此时也就是对象被销毁的时候。
二、注意
destroy()方法只有在scope属性值为singleton时才会执行,
scope的作用见博客: 详述scope作用
如果将scope的值设置为prototype,则测试类中的代码便不会执行destroy()方法:
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">
<bean id="userInfo" class="club.affengkuang.vo.UserInfo" lazy-init="true" scope="prototype" init-method="init" destroy-method="destroy">
<property name="name" value="Tom"></property>
</bean>
</beans>