CSDN专家博客精华版

为人民服务!
  首页  :: 新随笔  :: 管理

在Spring中使用replaced-method来进行方法替换

Posted on 2007-12-17 10:28  csdnexpert  阅读(251)  评论(0)    收藏  举报
  我们知道,通过使用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