随笔-42  评论-349  文章-4  trackbacks-0
 

        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接口,再为其添加nameage成员,GeterSeter方法,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 

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

 1 <?xml version="1.0" encoding="UTF-8"?>
 2 <beans
 3     xmlns="http://www.springframework.org/schema/beans"
 4     xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
 5 
 6     xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd">
 7     <bean id="animal" class="ioc.test.Animal">
 8 
 9       <property name="age"  value="5"></property>
10       <property name="name" value="猪"></property>
11 
12     </bean>
13 
14 </beans>
15 

新建含有主方法的TestMain类,添加测试代码,如下:
 1 package ioc.test;
 2 
 3 import org.springframework.context.support.AbstractApplicationContext;
 4 import org.springframework.context.support.ClassPathXmlApplicationContext;
 5 
 6 public class TestMain {
 7 
 8     public static void main(String[] args) {
 9 
10         AbstractApplicationContext ac = new ClassPathXmlApplicationContext("applicationContext.xml");
11         //注册容器关闭钩子,才能关掉容器,调用析构方法
12         ac.registerShutdownHook();
13         Animal animal = (Animal)ac.getBean("animal");
14         System.out.println(animal.speak());    
15     
16     }    
17 }
18 
 

运行工程,结果如下:

 

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

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


By:残梦追月
posted on 2008-07-28 14:24 残梦追月 阅读(1447) 评论(0)  编辑  收藏 所属分类: Spring

只有注册用户登录后才能发表评论。


网站导航: