9.02-Spring IOC 容器中Bean的生命周期

Spring IOC 容器能够管理Bean的生命周期,Spring 容许在Bean的生命周期的特定点执行定制的任务。spring

Spring IOC  容器中 Bean  的生命周期以下:
① .  经过构造器或工厂方法建立 Bean  实例 : 调用构造器
② .  为 Bean的属性设置值和对其余 Bean的引用 : 调用 setter
③ .  将 Bean给实例传递给Bean后置处理器的postProcessBeforeInitialization  方法
④ .  调用 Bean的初始化方法 : init-method
⑤ .  将Bean实例传递给 Bean后置处理器的postProcessAfterInitialization  方法
⑥ .  Bean  能够使用了
⑦ .  当容器关闭时 ,  调用 Bean  的销毁方法 : destroy- - method 。ide

    Bean  的初始化和销毁方法:能够经过 bean 节点的 init-method 和destroy-method 来配置 Bean 的初始化方法和销毁方法:post

<bean id="person" class="com.atguigu.spring.lifecycle.Person"
 init- - method="init"
 destroy- - method="destroy">
 <property name="name" value="abcd"></property> 
</bean>

    注意:ApplicationContext 接口中没有关闭容器的方法,因此使用ApplicationContext 接口做为 IOC 容器的引用,destroy-method 将不会起到做用 , 须要使用ApplicationContext 的子接口ConfigurableApplicationContext。ui

 

详解Bean后置处理器:3d

Bean后置处理器:Spring提供的特殊的Beancode

     ①. Bean 后置处理器容许在调用初始化方法(即:bean 节点 init-method属性对应的方法的先后)先后对 Bean 进行额外的处理.
     ②. Bean 后置处理器对 IOC 容器里的全部 Bean 实例逐一处理, 而非单一实例. 其典型应用是: 检查 Bean 属性的正确性或根据特定的标准更改 Bean的属性.
    ③. 对 Bean 后置处理器而言, 须要实现 BeanPostProcessor 接口blog

pulic class PersonPostProcessor implements BeanPostProcessor{
  /**
   *  arg0: IOC容器中bean的实例
   *  arg1: IOC容器中该bean的名字
   */
  @Override
  public Object postProcessorAfterInitialization(Object arg0,String arg1) throws BeansException{
    if(arg0 instanceof Person){
      System.out.println("postProcessorAfterInitialization");
      Person person=(Person)arg0;

      String name=person.getName();
      if(!name.equals("AAAA")){
        System.out.println("name值必须为AAAA!");
        person.setName("AAAA");
      }
    } 
    return arg0;
  }

  @Override
  public Object postProcessBeforeInitialization(Object arg0,String arg1) throws BeansException {
    System.out.println("postProcessBeforeInitialization");    
    return arg0;
  }
}

④. Bean 后置处理器须要在 IOC 容器中进行配置,但不须要指定 id 属性,Spring IOC 容器会自动的识别这是个 Bean 后置处理器,自动的使用它。接口

<bean class="com.atguigu.spring.lifecycle.PersonPostProcessor"/>
相关文章
相关标签/搜索