Spring4.0学习笔记(5) —— 管理bean的生命周期

时间:2024-06-01 19:06:14

Spring IOC 容器可以管理Bean的生命周期,Spring允许在Bean生命周期的特定点执行定制的任务

Spring IOC 容器对Bean的生命周期进行管理的过程:

1、通过构造器或工厂方法创建Bean的实例

2、为Bean的属性设置值和对其他Bean的引用

3、调用Bean的初始化方法

4、Bean可以使用了

5、当容器关闭时,调用Bean的销毁方法

bean文件

package com.spring.cycle;

public class Car {

    public Car(){
System.out.println("Car's constructor...");
} @Override
public String toString() {
return "Car [brand=" + brand + "]";
} private String brand; public void setBrand(String brand){
System.out.println("setBrand...");
this.brand = brand;
} public void init(){
System.out.println("init...");
} public void destroy(){
System.out.println("destroy...");
} }

配置文件

<?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-3.0.xsd"> <bean id="car" class="com.spring.cycle.Car" init-method="init" destroy-method="destroy">
<property name="brand" value="Audi"></property>
</bean> <bean class="com.spring.cycle.MyBeanPostProcesser">
</bean>
</beans>
package com.spring.cycle;

import org.springframework.context.support.ClassPathXmlApplicationContext;

public class main {
public static void main(String[] args) {
ClassPathXmlApplicationContext ctx = new ClassPathXmlApplicationContext("bean-cycle.xml");
Car car = (Car)ctx.getBean("car");
System.out.println(car);
//关闭IOC容器
ctx.close();
}
}

postProcessAfterInitialization 和 postProcessBeforeInitialization

package com.spring.cycle;

import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.BeanPostProcessor; public class MyBeanPostProcesser implements BeanPostProcessor { public Object postProcessAfterInitialization(Object arg0, String arg1)
throws BeansException {
System.out.println("postProcessAfterInitialization"+arg1);
return arg0;
} public Object postProcessBeforeInitialization(Object arg0, String arg1)
throws BeansException {
System.out.println("postProcessBeforeInitialization"+arg1);
return arg0;
} }

bean的生命周期

Car's constructor... 【调用构造器】
setBrand... 【设置属性】
postProcessBeforeInitializationcar 【实例化方法前】
init...【实例化bean】
postProcessAfterInitializationcar 【实例化方法后】
Car [brand=Audi] 【调用toString()方法】
destroy... 【销毁bean】