1.一個代理模式的實例 通過 Proxy類進行代理
wait.java
//定義一個接口 public interface wait { void say(); }
//目標對象實現接口並重寫方法 public class waiter implements wait { @Override public void say() { // TODO Auto-generated method stub System.out.println("先生"); } }
public class SayHelloBeforemale implements MethodBeforeAdvice {//實現相應增強類的接口 @Override public void before(Method arg0, Object[] arg1, Object arg2) throws Throwable { //arg0 是 目標類的方法 arg1是目標類的入參數 arg2是目標類實例 發生異常則拋給Throwable // TODO Auto-generated method stub System.out.println("hello"); } }
UnitTest.java
public class UnitTest { //實明變量 private SayHelloBeforemale male ; private waiter wait; private ProxyFactory xy; @Before public void init(){ //實例化並賦值 male = new SayHelloBeforemale(); wait = new waiter(); xy = new ProxyFactory(); //設置目標對象 xy.setTarget(wait); //設置增強類對象 xy.addAdvice(male); } @Test public void test(){ // waiter w = (waiter)xy.getProxy(); w.say(); }
2.通過spring的配置文件進行代理
這個方法進行代理所需的類和上面的 wait接口 和 它的實現類waiter 還有sayhelloadvice類
不同之處在於不是使用 ProxtyFactory來進行代理目標對象,而是通過Schema 的xml文件進行配置代理。
beans.xml
<bean id="sayhelloadvice" class="test3.SayHelloBeforemale"/> <bean id="target" class="test3.waiter"/> <bean id="waiter" class="org.springframework.aop.framework.ProxyFactoryBean" p:proxyInterfaces="test3.wait" p:interceptorNames="sayhelloadvice" p:target-ref="target" />
- target:代理的目標對象
- proxyInterfaces:代理所需要實現的接口,可以多個接口。該屬性還有一個別名是Interfaces
- interceptorNames:需要植入目標對象的bean列表。采用bean的名稱指定。這些bean必須實現類 org.aopalliance.intercept.MethodInterceptor
或 org.springframework.aop.Advisor的bean ,配置中的順序對應調用的順序。
- proxyTargetClass:是否對類進行代理(而不是進行對接口進行代理),設置為true時,使用CGLib代理,且proxyInterfaces屬性被ProxyFactoryBean忽略。
UnitTest.java
public class UnitTest { @Test //測試在spring 通過ProxyFactoryBean 配置代理 public void test2(){ ApplicationContext a = new ClassPathXmlApplicationContext("test3/beans.xml"); wait w = (wait)a.getBean("waiter"); w.say(); } }