Spring bean生命周期

我相信对于很多人来说,干说的理解速度比例子差很多,因此我们先上例子:

public class Student {

	private String age;
	
	static {
		System.out.println("静态代码块");
	}
	
	{
		System.out.println("非静态代码块");
	}
	
	public Student() {
		System.out.println("构造方法");
	}

	public String getAge() {
		System.out.println("get方法");
		return age;
	}

	public void setAge(String age) {
		System.out.println("set方法");
		this.age = age;
	}
	
	public void init() {
		System.out.println("init初始化方法");
	}
	
	public void destroy() {
		System.out.println("destroy销毁方法");
	}
}

我们在 Student 类中先后定义了以上5种方法加2个代码块;且每个方法或代码块都有一个输出语句用于标识程序执行的先后顺序;然后我们再在 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 id= "student" class="com.jd.vo.Student" p:age="12" init-method="init" destroy-method="destroy"></bean>
	
</beans>

p:age="12" 是对创建的 Student 对象的 age 属性进行赋值;而 init-method="init" 则是调用 bean 的初始化方法,使用 init-method="init" 指定初始化方法为 Student 类中的 init() 方法;而IOC容器关闭时,则使用 destroy-method="destroy" 调用 bean 的销毁方法并指定为  Student 类中的 destroy() 方法;

import org.springframework.context.support.ClassPathXmlApplicationContext;

import com.jd.vo.Student;

public class Test {

	public static void main(String[] args) {
		ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("application.xml");
	}
}

Test.java 中我们直接启用IOC容器,然后对象创建,因此我们可以在控制台得到以下显示:

我们可以看出,bean 中创建对象过程中代码的执行顺序为 :静态代码块 ---> 非静态代码块 ---> 构造方法 ---> set 方法(为 bean 赋值)---> bean 初始化方法 init-method

之后我们再在之前 Test.java 的的基础上添加三行代码,如下:

import org.springframework.context.support.ClassPathXmlApplicationContext;

import com.jd.vo.Student;

public class Test {

	public static void main(String[] args) {
		ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("application.xml");
		Student student = (Student) context.getBean("student");
		System.out.println(student.getAge());
		context.close();
	}
}

这次我们增加了对创建的 Student 对象的操作代码以及 IOC容器 关闭的代码;控制台效果如下:

我们可以看出,对对象的操作是在 bean 初始化完成之后,而销毁方法则是在 Spring IOC容器 关闭时执行;加上之上的执行顺序我们再看 bean 的生命周期:

静态代码块 ---> 非静态代码块 ---> 构造方法 ---> set 方法(为 bean 赋值)---> bean 初始化方法 init-method ---> 对对象进行操作 ---> 关闭IOC容器时执行 destroy-method 方法

注意:a、init-method:在设置 bean 的属性后执行的自定义初始化方法,注意:①、该方法不能有参数;②、对象每创建一次就会执行一次该方法;

b、destroy-method:该参数中的方法只有 bean 标签属性 scope 为 singleton 且关闭Spring IOC容器时才会被调用,注意:该方法不能有参数(若 bean 中未注明 scope 属性,则默认为 singleton )。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值