[转载]快速上手Spring--10. 任意方法的替换

快速上手Spring--10. 任意方法的替换
这篇文章来谈谈 《Spring Framework 开发参考手册》 的3.3.3.2小节中的“任意方法的替换”。
仔细看看文档
· 先建立一个包:javamxj.spring.basic.MethodReplacer ,然后把以下5个文件放在这个包下。
Hello.java
package javamxj . spring . basic . MethodReplacer ;

public interface Hello {
public void sayHello( String s);
}
HelloImpl.java
package javamxj . spring . basic . MethodReplacer ;

public class HelloImpl implements Hello {
public void sayHello( String name) {
System.out.println( "Hello: " + name);
}
}
HelloReplacer.java
package javamxj . spring . basic . MethodReplacer ;

import java . lang . reflect . Method ;

import org . springframework . beans . factory . support . MethodReplacer ;

public class HelloReplacer implements MethodReplacer {
public Object reimplement( Object o, Method m, Object[] args) throws Throwable {

System.out.println( "你好: " + args[0]);
return null;
}
}
beans.xml
xml version = " 1.0 " encoding = " GBK " ?>
DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN//EN" "http://www.springframework.org/dtd/spring-beans.dtd">

<beans>
<bean id="helloReplacer" class="javamxj.spring.basic.MethodReplacer.HelloReplacer"/>

<bean id="helloA" class="javamxj.spring.basic.MethodReplacer.HelloImpl"/>

<bean id="helloB" class="javamxj.spring.basic.MethodReplacer.HelloImpl">
<replaced-method name="sayHello" replacer="helloReplacer"/>
bean>

beans>
Main.java
package javamxj . spring . basic . MethodReplacer ;

import org . springframework . beans . factory . BeanFactory ;
import org . springframework . beans . factory . xml . XmlBeanFactory ;
import org . springframework . core . io . ClassPathResource ;
import org . springframework . core . io . Resource ;

public class Main {
public static void main( String[] args) {
Resource res = new ClassPathResource(
"javamxj/spring/basic/MethodReplacer/beans.xml");
BeanFactory ft = new XmlBeanFactory(res);

// 没有使用replaced-method
Hello h = (Hello) ft.getBean( "helloA");
h.sayHello( "分享Java快乐");

// 使用replaced-method
h=(Hello) ft.getBean( "helloB");
h.sayHello( "分享Java快乐");

}
}
简单说明一下:

· Hello是一个接口类,实现面向接口编程。

· HelloImpl类实现了Hello接口,简单的输出一个语句。

· HelloReplacer类要实现MethodReplacer接口,reimplement中提供替换后的方法。

· beans.xml中定义了三个bean,helloReplacer指向HelloReplacer类;helloA和helloB都指向HelloImpl类,其中helloB中定义了replaced-method。

· 在Main类中,对比输出使用replaced-method前后的语句。

· 这次需要将 spring-framework主目录libcglib 目录中的cglib-nodep-2.1_2.jar加入到项目的 Libraries中,使用其中的动态代理。
运行结果:
Hello: 分享Java快乐
你好: 分享Java快乐

来自 “ ITPUB博客 ” ,链接:http://blog.itpub.net/374079/viewspace-131215/,如需转载,请注明出处,否则将追究法律责任。

转载于:http://blog.itpub.net/374079/viewspace-131215/

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值