Dog.java
package com.han;
import com.han.factory.MyProxyFactory;
public class Test {
public static void main(String []args)
{
Dog target=new GunDog();
Dog dog=(Dog)MyProxyFactory.getProxy(target);
dog.info();
dog.run();
}
}
GunDog.java
package com.han;
public class GunDog implements Dog{
@Override
public void info() {
// TODO Auto-generated method stub
System.out.println("我是一只猎狗");
}
@Override
public void run() {
// TODO Auto-generated method stub
System.out.println("我奔跑迅速");
}
}
TxUtil.java
package com.han.intercepter;
/*********
* 拦截器
* *********/
public class TxUtil {
//|拦截器:模拟事务开始
public void BeginTx(){
System.out.println("==模拟开始事务==");
}
//|拦截器:模拟事务结束
public void EndTx()
{
System.out.println("==模拟结束事务==");
}
}
MyInvocationHandler.java
package com.han.Handler;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import com.han.intercepter.TxUtil;
public class MyInvokationHandler implements InvocationHandler{
//|需要被代理的对象
private Object target;
public void setTarget(Object target) {
this.target = target;
}
//|执行动态代理的所有方法时 都会被替换成如下的invoke方法(重点)
@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
// TODO Auto-generated method stub
TxUtil tx=new TxUtil();
tx.BeginTx();
//|调用 target的 method方法 传入args参数(重点)(返回method方法的返回结果)
Object result=method.invoke(target, args);
tx.EndTx();
return result;
}
}
MyProxyFactory.java
package com.han.factory;
import java.lang.reflect.Proxy;
import com.han.Handler.MyInvokationHandler;
public class MyProxyFactory {
public static Object getProxy(Object target)
{
MyInvokationHandler handler=new MyInvokationHandler();
handler.setTarget(target);
//|创建并且返回一个动态代理
return Proxy.newProxyInstance(target.getClass().getClassLoader(), target.getClass().getInterfaces(), handler);
}
}
Test.java
package com.han;
import com.han.factory.MyProxyFactory;
public class Test {
public static void main(String []args)
{
Dog target=new GunDog();
Dog dog=(Dog)MyProxyFactory.getProxy(target);
dog.info();
dog.run();
}
}
运行结果:
==模拟开始事务==
我是一只猎狗
==模拟结束事务==
==模拟开始事务==
我奔跑迅速
==模拟结束事务==