Spring IOC 容器对 Bean 的生命周期进行管理的过程:
通过构造器或工厂方法创建 Bean 实例
为 Bean 的属性设置值和对其他 Bean 的引用
将 Bean 实例传递给 Bean 后置处理器的 postProcessBeforeInitialization 方法
调用 Bean 的初始化方法
将 Bean 实例传递给 Bean 后置处理器的 postProcessAfterInitialization方法
Bean 可以使用了
当容器关闭时, 调用 Bean 的销毁方法

beans-cycle.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="car" class="com.aff.spring.beans.cycle.Car" init-method="init2" destroy-method="detory">
<property name="brand" value="Audi" />
</bean>
<!--实现 BeanPostProcessor -->
<!--配置bean 的后置处理器 并具体实现
postProcessBeforeInitialization :init-method 之前被调用
postProcessAfterInitialization :init-method 之后被调用
方法的实现 bean bean 实例本身
beanName : IOC 容器配置的bean名字
返回值: 是实际上返回给用户的哪个bean 注意: 可以在以上两个方法中修改返回bean , 甚至 返回一个新的bean
-->
<!--配置 -->
<bean class="com.aff.spring.beans.cycle.MyBeanPostProcessor"></bean> </beans>

MyBeanPostProcessor.java

package com.aff.spring.beans.cycle;

import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.BeanPostProcessor; public class MyBeanPostProcessor implements BeanPostProcessor { @Override
public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {
System.out.println("postProcessBeforeInitialization:"+bean+","+beanName);
if ("car".equals(beanName)) {
//...
}
return bean;
} @Override
public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
System.out.println("postProcessAfterInitialization:"+bean+","+beanName);
Car car = new Car();
car.setBrand("ford");
return car;
}
}

Main

package com.aff.spring.beans.cycle;

import org.springframework.context.support.ClassPathXmlApplicationContext;

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

 Car

package com.aff.spring.beans.cycle;

public class Car {
public Car() {
System.out.println("Car's Construct...");
} private String brand; public void setBrand(String brand) {
System.out.println("set Brand...");
this.brand = brand;
} public void init2() {
System.out.println("init...");
} public void detory() {
System.out.println("destory ...");
} @Override
public String toString() {
return "Car [brand=" + brand + "]";
} }
05-11 13:38