Chinaunix首页 | 论坛 | 博客
  • 博客访问: 545221
  • 博文数量: 136
  • 博客积分: 4010
  • 博客等级: 上校
  • 技术积分: 1343
  • 用 户 组: 普通用户
  • 注册时间: 2008-08-19 23:18
文章分类

全部博文(136)

文章存档

2011年(28)

2009年(60)

2008年(48)

我的朋友

分类: Java

2011-07-06 19:47:59

Spring 里面涉及到一个概念叫做生命周期回调函数,意思是在SPring生命周期开始和结束的时候回调的函数。

其中生命周期开始的回调函数会在被设置的Bean读取所有依赖的Bean后才回调。销毁回调函数会在Bean销毁之前回调

Spring中可以有3中方法指定回调函数。

1,在Spring的配置文件中对Bean进行设置

    例如对name为exampleInitBean的Bean的设置器生命周期开始的回到函数为init

    <beanid="exampleInitBean"class="examples.ExampleBean"init-method="init"/>

    设置Bean生命周期结束时候的回调函数

    <beanid="exampleInitBean"class="examples.ExampleBean"destroy-method="cleanup"/>

 

2.不采用spring 的xml配置文件,即不设置bean的init-mothod和destroy-method属性。

  则在bean的实现类(非接口)上分别实现InitializingBean 和 DisposableBean 接口

初始化时的回调函数:

<beanid="exampleInitBean"class="examples.ExampleBean" />

public class AnotherExampleBean implements InitializingBean { 
    publicvoid afterPropertiesSet() { 
        // do some initialization work 
    }
}

销毁时的回调函数:

public class AnotherExampleBean implements DisposableBean {

  public void destroy() {
      // do some destruction work (like releasing pooled connections)

  }
}

 

3.采用注解的方式。分别采用 @PostConstruct 和 @PreDestroy 标签

 

在xml配置中可以配置一个全局的回调方法,只要在其的父标签标签里面设置其init-method 和 destroy-method属性即可,如果里面其中一个bean不用全局的回调方法,在此bean中设置该bean的Init-method和destroy-method即可

 

 假如一个bean采用了多个初始化回调函数或者销毁前回调函数的设置的时候,其实在spring有这样的一个执行次序的机制。次序如下所示:

初始化回调函数:

1.设置@PostConstruct标签

2.类实现IntializationBean接口

3.在xml配置文件中配置了bean的init-method属性

销毁前回调函数的执行次序:

1.设置了@PreDestroy标签

2.类实现了DisposibleBean接口

3.在xml配置文件中配置了bean的destroy-method属性

 

 

阅读(1823) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~