IOC容器中bean的生命周期方法-Spring IOC容器可以管理bean的生命周期,Spring允许在bean的生命周期的特定点执行定制的任务-Spring IOC容器对bean的生命周期进行管理的过程:
-在bean的声明里设置init-method和dectory-method属性,为bean指定初始化和销毁方法创建bean后置处理器-bean后置处理器允许在调用初始化方法前后对bean进行额外的处理-bean后置处理器对IOC容器里所有bean实例逐一处理,而非单一实例。其典型应用是:检查bean属性的正确性或根据特定的标准更改bean的属性-对bean后置处理器而言,需要实现Interface BeanPostProcessor接口。在初始化方法被调用前后,Spring将把每个bean实例分别传递给上述接口的以下两个方法-postProcessBeforeInitialization-postProcessAfterInitialization添加bean后置处理器后bean的生命周期
bean的配置文件:
1 <?xml version="1.0" encoding="UTF-8"?> 2 <beans xmlns="http://www.springframework.org/schema/beans" 3 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 4 xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd"> 5 6 <bean id="car" class="com.yl.cycle.Car" 7 init-method="init" destroy-method="destory"> 8 <property name="brand" value="Audi"></property> 9 </bean>10 11 12 <!-- 实现BeanPostProcessor接口,并且提供13 Object postProcessBeforeInitialization(Object bean, String beanName) init-method方法之前调用14 Object postProcessAfterInitialization(Object bean, String beanName) init-method方法之后调用15 的实现16 bean:bean实力本身17 beanName:IOC容器中配置的bean的名字18 返回值是实际上返回给用户的那个bean,注意:可以在以上两个方法中修改返回的bean,设置返回一个新的bean19 -->20 <!-- 配置bean的后置处理器 。 不需要配置id,IOC容器自动识别是一个BeanPostProcessor-->21 <bean class="com.yl.cycle.MyBeanPostProcessor"></bean>22 23 </beans>
bean的后置处理器:
1 package com.yl.cycle; 2 3 import org.springframework.beans.BeansException; 4 import org.springframework.beans.factory.config.BeanPostProcessor; 5 6 public class MyBeanPostProcessor implements BeanPostProcessor { 7 8 @Override 9 public Object postProcessAfterInitialization(Object bean, String beanName)10 throws BeansException {11 System.out.println("postProcessAfterInitialization: " + bean + ", " + beanName);12 13 Car car = new Car();14 car.setBrand("Ford");15 16 return car;17 }18 19 @Override20 public Object postProcessBeforeInitialization(Object bean, String beanName)21 throws BeansException {22 System.out.println("postProcessBeforeInitialization: " + bean + ", " + beanName);23 24 if ("car".equals(beanName)) {25 26 }27 28 29 return bean;30 }31 32 }
测试类:
1 package com.yl.cycle; 2 3 import org.springframework.context.applicationContext; 4 import org.springframework.context.support.AbstractApplicationContext; 5 import org.springframework.context.support.ClassPathXmlApplicationContext; 6 7 public class CycleMain { 8 public static void main(String[] args) { 9 ApplicationContext ctx = new ClassPathXmlApplicationContext("beans-cycle.xml");10 11 Car car = (Car)ctx.getBean("car");12 System.out.println(car);13 14 //关闭容器15 ((AbstractApplicationContext) ctx).close();16 }17 }
新闻热点
疑难解答