生命周期
通过构造方法或工厂方法创建bean对象——>为bean属性赋值——>调用 bean 的初始化方法,即init-method指定方法——>bean实例化完毕,可以使用——>容器关闭, 调用 bean 的销毁方法,即destroy-method指定方法。其中:
init-method
在设置bean的属性后执行的自定义初始化方法。
注意:①、该方法不能有参数;②、对象每创建一次就会执行一次该方法。
package com.spring.test;
public class Student {
private String name;
public Student() {
System.out.println("构造方法");
}
public String getName() {
return name;
}
public void setName(String name) {
System.out.println("setter方法");
this.name = name;
}
public void init() {
System.out.println("初始化方法");
}
}
<bean class="com.spring.test.Student" init-method="init">
<property name="name" value="小王"></property>
</bean>
Test类
ClassPathXmlApplicationContext application = new ClassPathXmlApplicationContext("application.xml");
Student student = application.getBean(Student.class);
System.out.println(student.getName());
application.close();
结果
destroy-method
该参数中的方法只有bean标签属性scope为singleton且关闭Spring IOC容器时才会被调用。
注意:该方法不能有参数
package com.spring.test;
public class Student {
private String name;
public void destroy() {
System.out.println("destroy-method");
}
public void setName(String name) {
this.name=name;
System.out.println(name);
}
public String getName() {
return name;
}
}
<bean class="com.spring.test.Student" destroy-method="destroy" scope="singleton">
<property name="name" value="小王"></property>
</bean>
Test类
ClassPathXmlApplicationContext application = new ClassPathXmlApplicationContext("application.xml");
Student student = application.getBean(Student.class);
System.out.println(student);
application.close();
结果
如果“scope”不为单例,而为多例时,则不调用destory方法。
<bean class="com.spring.test.Student" destroy-method="destroy" scope="prototype">
<property name="name" value="小王"></property>
</bean>
结果