空间站

北极心空

  BlogJava :: 首页 :: 联系 :: 聚合  :: 管理
  15 Posts :: 393 Stories :: 160 Comments :: 0 Trackbacks
我们知道,通过使用Spring的AOP,可以非常容易的增强类中一些方法的功能,或者是替换掉一个方法。这里简单介绍一种不使用Spring AOP,而是Spring IOC中内置的一种方法替换功能。即<bean>标签中<replaced-method>元素的应用。
 
   在Spring的配置文件中,在配置一个Bean的时候,可以使用该元素(标签)用来设置方法替换。 <replaced-method>标签的name属性用来指定要替换的方法名称,replacer属性用来指定用来替换的Bean,这个Bean要求实现Spring的MethodReplacer接口。该标签下面的arg-type元素用来指定0个或多个方法参数。下面我们看一个简单的例子:
 public class LookupMethodBean {
 public void test()
 {
  System.out.println("原始方法!");
 }
 }
 
 MethodReplace.java
import java.lang.reflect.Method;
import org.springframework.beans.factory.support.MethodReplacer;
public class MethodReplace implements MethodReplacer {
 public Object reimplement(Object obj, Method method, Object[] args)
   throws Throwable {
    System.out.println("方法已经被替换!");
  return null;
 }
}

Spring配置文件部分内容
 <bean name="replacer" class="springroad.deomo.chap4.MethodReplace"> 
 </bean> 
 <bean name="testBean" class="springroad.deomo.chap4.LookupMethodBean">
  <replaced-method name="test" replacer="replacer"> </replaced-method> 
 </bean> 
 
  这样,testBean的test方法被替换,在调用testBean的test方法时,将执行replcacer这个Bean中的reimplement方法。 


Trackback: http://tb.blog.csdn.net/TrackBack.aspx?PostId=1344361

posted on 2006-11-24 22:22 芦苇 阅读(1920) 评论(0)  编辑  收藏 所属分类: Spring

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


网站导航: