首先,我们在一个类中写下与生命周期相关的多种元素
package com.jd.vo;
public class UserInfo {
static {
System.out.println("静态代码块");
}
{
System.out.println("非静态代码块");
}
private String name;
public String getName() {
System.out.println("getter方法");
return name;
}
public void setName(String name) {
System.out.println("setter方法");
this.name = name;
}
public UserInfo() {
System.out.println("构造方法");
}
public void init() {
System.out.println("init");
}
public void destroy() {
System.out.println("destroy");
}
}
并创建test类来测试其输出
package com.jd.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("d");
applicationContext.close();
}
}
配置xml文件
<?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="d" class="com.jd.vo.UserInfo" lazy-init="true" scope="prototype">
<property name="name" value="Tom"></property>
</bean>
</beans>
执行main方法,输出为
可以看到spring对象的生命周期为静态代码块->动态代码块->构造方法->set方法,我们注意到,由于init和destroy的值均为默认,导致init方法和destroy方法未能输出。
修改xml文件如下所示
<?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="d" class="com.jd.vo.UserInfo" lazy-init="true" scope="prototype" init-method="init" destroy-method="destroy">
<property name="name" value="Tom"></property>
</bean>
</beans>
输出为
我们发现,init方法在setter之后输出了,但destroy方法仍未输出,这是由于scope的值设定为了prototype,如果我们改为singlton,输出则变为
并且如果我们在main方法中没有调用close方法销毁IoC容器,那么destroy方法也不会输出。
综上,spring对象的生命周期为静态代码块->动态代码块->构造方法->setter方法->getter方法->init->destroy