Spring4IOC容器中Bean的生命周期方法

  • SpringIOC容器可以管理Bean的生命周期,Spring允许在Bean的生命周期的特定点执行定制的任务
  • SpringIOC容器对Bean的生命周期进行管理的过程:

         ——通过构造器或工厂方法创建Bean实例

         ——为Bean的属性设置和对其他Bean的引用

         ——调用Bean的初始化方法

         ——Bean可以使用了

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

  • 在Bean的声明里设置init-method和destroy-method属性,为Bean指定初始化和销毁方法。


     Bean后置处理器
  • Bean后置处理器允许在调用初始化方法前后对Bean进行额外处理。
  • Bean后置处理器对IOC容器里的所有Bean实例逐一处理,而非单一实例。其典型应用是:检查Bean属性的正确性或根据特定的标准更改Bean的属性。
  • 对Bean后置处理器而言,需要实现org.springframework.beans.factory.config Interface BeanPostProcessor接口.在初始化方法被调用前后,Spring将把每个Bean实例分别传递给上述接口的一下两个方法:
           Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException;
          Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException;
实例:
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>
	
	<bean class="com.atguigu.spring.beans.cycle.MyBeanPostProcessor"></bean>
</beans>





你可能感兴趣的:(Spring4IOC容器中Bean的生命周期方法)