这篇文章来谈谈
《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主目录/lib/cglib 目录中的cglib-nodep-2.1_2.jar加入到项目的 Libraries中,使用其中的动态代理。
· Hello是一个接口类,实现面向接口编程。
· HelloImpl类实现了Hello接口,简单的输出一个语句。
· HelloReplacer类要实现MethodReplacer接口,reimplement中提供替换后的方法。
· beans.xml中定义了三个bean,helloReplacer指向HelloReplacer类;helloA和helloB都指向HelloImpl类,其中helloB中定义了replaced-method。
· 在Main类中,对比输出使用replaced-method前后的语句。
· 这次需要将 spring-framework主目录/lib/cglib 目录中的cglib-nodep-2.1_2.jar加入到项目的 Libraries中,使用其中的动态代理。
运行结果:
Hello: 分享Java快乐
你好: 分享Java快乐
你好: 分享Java快乐
这篇文章源代码下载(不包含库文件):
http://free.ys168.com/?javamxj
Spring目录下面的SpringBasic.zip。