目录
bean标签的生命周期
- 调用构造方法创建bean对象
- 调用setter方法为属性赋值
- 调用 bean 的初始化方法,即init-method指定方法
- bean实例化完毕,可以使用
- 容器关闭, 调用 bean 的销毁方法,即destroy-method指定方法。
- 如若最前面有静态代码块和非静态代码块,则先执行静态代码块,再执行非静态代码块,之后再执行1~5步。
init-method:在设置bean的属性后执行的自定义初始化方法。
注意:①、该方法不能有参数;②、对象每创建一次就会执行一次该方法;
destroy-method:该参数中的方法只有bean标签属性scope为singleton且关闭Spring IOC容器时才会被调用。
注意:该方法不能有参数
应用举例
首先在exlipse工具里创建一个Java工程如下:
进行相关的配置以及考入相应的jar包后
application.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"
xmlns:p="http://www.springframework.org/schema/p"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">
<bean class="com.zzu.vo.Student" destroy-method="destroy"
init-method="init" p:name="Tim">
</bean>
</beans>
注意这里的相关勾选:
Student里的代码如下:
package com.zzu.vo;
public class Student {
//bean标签属性
private String name;
static{
System.out.println("static静态代码块");
}
{
System.out.println("not static非静态代码块");
}
public Student() {
System.out.println("构造方法");
}
public void setName(String name) {
System.out.println("Tim setter方法");
this.name = name;
}
public void init() {
System.out.println("init初始化方法");
}
public void destroy() {
System.out.println("destroy销毁方法");
}
}
Test里的代码如下:
package com.zzu.test;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import com.zzu.vo.Student;
public class Test {
public static void main(String[] args) {
ClassPathXmlApplicationContext application=
new ClassPathXmlApplicationContext("application.xml");
Student student = application.getBean(Student.class);
System.out.println(student);
application.close();
}
}
执行结果如下:
注意:这里在控制台输出的结果的顺序是固定的,是按照顺序执行的,并不会因application.xml里<bean class="com.zzu.vo.Student" destroy-method="destroy" init-method="init" p:name="Tim"></bean>中的配置顺序变化而变化。