Spring管理Bean的生命周期
笔记内容及代码来源于尚硅谷的免费在线课
地址:http://www.gulixueyuan.com/my/course/46
Spring IOC容器对Bean的生命周期进行管理的过程:
1.通过构造器或工厂方法创建Bean实例
2.为Bean的属性设置值和对其他Bean的引用
3.将Bean实例传递给Bean后置处理器的postProcessBeforeInitialization方法
4.调用Bean的初始化方法
5.将Bean实例传递给Bean后置处理器的postProcessAfterInitialization方法
6.Bean可以使用了
7.当容器关闭时,调用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" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd"> <bean id="car" class="com.atguigu.spring.beans.cycle.Car" init-method="init" destroy-method="destroy"> <property name="brand" value="Audi"></property> </bean> <!-- 实现BeanPostProcessor接口,并具体提供 Object postProcessBeforeInitialization(Object bean,String beanName): init-method 之前被调用 Object postProcessAfterInitialization(Object bean,String beanName): init-metho d 之前被调用 bean:bean实例本身 beanName:IOC容器中,配置的bean的名字 返回值:实际上返回给用户的Bean,可以在以上两个方法中修改返回的bean,甚至返回一个新的bean --> <!--配置bean的后置处理器:不需要配置id,IOC容器自动识别是一个BeanPostProcessor--> <bean class="com.atguigu.spring.beans.cycle.MyBeanPostProcessor"></bean> </beans>
MyBeanPostProcessor.java
package com.atguigu.spring.beans.cycle; import org.springframework.beans.BeansException; import org.springframework.beans.factory.config.BeanPostProcessor; public class MyBeanPostProcessor implements BeanPostProcessor { public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException { System.out.println("postProcessBeforeInitialization: " + bean+","+beanName); return bean; } public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException { System.out.println("postProcessAfterInitialization: " + bean+","+beanName); Car car = new Car(); car.setBrand("Ford"); return car; } }
Car.java
package com.atguigu.spring.beans.cycle; public class Car { public Car() { System.out.println("Car Constructor..."); } private String brand; public void setBrand(String brand) { this.brand = brand; System.out.println("setBrand"); } public void init(){ System.out.println("init....."); } public void destroy(){ System.out.println("destroy..."); } @Override public String toString() { return "Car{" + "brand='" + brand + '\'' + '}'; } }
main.java
package com.atguigu.spring.beans.cycle; import org.springframework.context.ApplicationContext; 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); ctx.close(); } }