Spring IoC容器的本质是管理Bean,对于Bean而言在容器中有其存在的生命周期。它的初始化和销毁也需要一个过程。Bean的生命周期主要了解Spring IoC容器初始化和销毁Bean的过程。为了定义安装和拆卸一个 bean,我们只要声明带有 init-method 和/或 destroy-method 参数的 。init-method 属性指定一个方法,在实例化 bean 时,立即调用该方法。同样,destroy-method 指定一个方法,只有从容器中移除 bean 之后,才能调用该方法。
Bean的生命周期可以表达为:Bean的定义——Bean的初始化——Bean的使用——Bean的销毁
1.1 定义Bean
这是Bean配置文件
<?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="HelloWorld" class="com.spring.chapter2.HelloWorld" init-method="init" destroy-method="destroy">
<property name="say" value="世界你好"></property>
</bean>
</beans>
1.2下面是HelloWorld.java的定义:
1 package com.spring.chapter2;
2
3 public class HelloWorld {
4
5
6 public String getSay() {
7 return say;
8 }
9 public void setSay(String say) {
10 this.say = say;
11 }
12 private String say;
13
14
15 public void init(){
16 System.out.println(say+"Bean 开始初始化...");
17
18 }
19 public void destroy(){
20 System.out.println(say+"Bean 开始销毁...");
21 }
22
23 }
2.1 下面是 Main.java 文件的内容。
1 public static void main(String[] args) {
2
3 AbstractApplicationContext applicationContext=newClassPathXmlApplicationContext("spring_xml/spring.xml");
4 HelloWorld helloWorld=(HelloWorld)applicationContext.getBean("HelloWorld");
5 System.out.println(helloWorld.getSay());
6 applicationContext.registerShutdownHook(); //AbstractApplicationContext 类中声明的关闭 hook 的 registerShutdownHook()方法。它将确保正常关闭,并且调用相关的 destroy 方法。
7 }
2.2测试结果
默认的初始化和销毁方法
如果你有太多具有相同名称的初始化或者销毁方法的 Bean,那么你不需要在每一个 bean 上声明初始化方法和销毁方法。框架使用 元素中的 default-init-method 和 default-destroy-method 属性提供了灵活地配置这种情况,如下所示:
1 <beans xmlns="http://www.springframework.org/schema/beans"
2 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
3 xsi:schemaLocation="http://www.springframework.org/schema/beans
4 http://www.springframework.org/schema/beans/spring-beans-3.0.xsd"
5 default-init-method="init"
6 default-destroy-method="destroy">
7
8 <bean id="..." class="...">
9 ...
10 </bean>
11
12 </beans>