Spring受管Bean的预处理和后处理二

使用回调接口对受管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;23 import org.springframework.beans.facTory.DisposableBean;4 import org.springframework.beans.facTory.InitializingBean;56 public class Animal implements InitializingBean, DisposableBean {78 private String name;9 private int age;1011 public String speak(){12 return "我的名字:"+this.name+"我的年龄:"+this.age;13 }1415 public void afterPropertiesSet() throws Exception {16 System.out.println("初始化接口afterPropertiesSet()方法正在运行!");17 }1819 public void destroy() throws Exception {20 System.out.println("析构接口destroy()方法正在运行!");21 }2223 //Geter和Seter省略2425 }26

在配置文件中配置受管Bean,代码如下:

1 2 3 xmlns="http://www.springframework.org/schema/beans"4 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"56 xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd">7 89 10 1112 1314 15

新建含有主方法的TestMain类,添加测试代码,如下:

1 package ioc.test;23 import org.springframework.context.support.AbstractApplicationContext;4 import org.springframework.context.support.ClassPathXmlApplicationContext;56 public class TestMain {78 public static void main(String[] args) {910 AbstractApplicationContext ac = new ClassPathXmlApplicationContext ("applicationContext.xml");11 //注册容器关闭钩子,才能关掉容器,调用析构方法12 ac.registerShutdownHook();13 Animal animal = (Animal)ac.getBean("animal");14 System.out.println(animal.speak());1516 }17 }18

运行工程,结果如下:

以看到,Spring IoC容器自动的调用了两个接口的相关方法对bean进行了预处理和后处理。

注意:由于后处理是在Bean被销毁之前调用,所有要在MyEclipse中看到后处理方法的输出,必须先注 册容器的关闭钩子,在主方法退出时关掉容器,这样其管理的Bean就会被销毁。当然也可以直接调用容器 的close方法来显示的关闭容器。

生活不是等待风暴过去,而是学会在雨中翩翩起舞。

Spring受管Bean的预处理和后处理二

相关文章:

你感兴趣的文章:

标签云: