Welcome 微信登录

首页 / 软件开发 / JAVA / Spring受管Bean的预处理和后处理 二

Spring受管Bean的预处理和后处理 二2011-10-02 残梦追月 使用回调接口对受管Bean进行与处理和后处理

1、初始化回调接口InitializingBean 要对某个受管Bean进行预处理里时,可以实现Spring定义的 初始化回调接口InitializingBean,它定义了一个方法如下:

1 void afterPropertiesSet() throws Exception

开发者可以在受管Bean中实现该接口,再在此方法中对受管Bean进行预处理。

注意:应该尽量避免使用这种方法,因为这种方法会将代码与Spring耦合起来。推荐使用下面的使用 init-method方法。

2、析构回调接口DisposableBean 同上面一样,要对受管Bean进行后处理,该Bean可以实现析构回 调接口DisposableBean,它定义的方法如下:

1 void destroy() throws Exception

为了降低与Spring的耦合度,这种方法也不推荐。

下面的例子(例程3.6)简要的展示如何使用这两个接口。

新建Java工程,名字为IoC_Test3.6,为其添加Spring开发能力后,新建一ioc.test包,添加一个 Animal类,该类实现InitializingBean接口和DisposableBean接口,再为其添加name和age成员,Geter和 Seter方法,speak方法。完成后代码如下:

1 package ioc.test;
2
3 import org.springframework.beans.factory.DisposableBean;
4 import org.springframework.beans.factory.InitializingBean;
5
6 public class Animal implements InitializingBean, DisposableBean {
7
8 private String name;
9 private int age;
10
11 public String speak(){
12 return "我的名字:"+this.name+"我的年龄:"+this.age;
13 }
14
15 public void afterPropertiesSet() throws Exception {
16 System.out.println("初始化接口afterPropertiesSet()方法正在运行!");
17 }
18
19 public void destroy() throws Exception {
20 System.out.println("析构接口destroy()方法正在运行!");
21 }
22
23 //Geter和Seter省略
24
25 }
26