* 模拟了给方法加入事务过程
接口——>
package com.xx.service;
public interface ProductService {
public void save();
public void get();
public void update();
}
实现类——>
package com.xx.service.impl;
import com.xx.service.ProductService;
public class ProductServiceBean implements ProductService {
public void get() {
System.out.println("这是get方法");
}
public void save() {
System.out.println("这是save方法");
}
public void update() {
System.out.println("这是update方法");
}
}
动态代理类工厂——>
package com.xx.proxyFactory;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import com.sun.corba.se.spi.orbutil.fsm.Guard.Result;
import com.sun.org.apache.bcel.internal.generic.NEW;
import com.xx.service.ProductService;
import com.xx.service.impl.ProductServiceBean;
/**
* 执行过程
* 1 传入目标对象;
* 2、根据目标对象生成代理对象;
* 3、代理对象的方法是目标对象的方法经过invoke方法返回的代理方法,
* 4、返回代理对象,客户端调用的方法是代理方法(相当于把目标对象的方法单独处理了一下);
*
*/
public class ProxyFactory implements InvocationHandler {
private Object tarObject;//目标对象
public Object getPropxy(Object targetObj){
this.tarObject = targetObj;
//生成代理对象
return Proxy.newProxyInstance(targetObj.getClass().getClassLoader(),
targetObj.getClass().getInterfaces(),
this);
}
public Object invoke(Object proxy, Method method, Object[] args)
throws Throwable {
Object result = null; //代理的方法,并将代理方法返回
before();
result = method.invoke(tarObject, args);
end();
return result;
}
public void before(){
System.out.println("-------事务开始--------");
}
public void end(){
System.out.println("-------事务结束--------");
}
}
客户端——>
package junit.test;
import org.junit.BeforeClass;
import org.junit.Test;
import com.xx.proxyFactory.ProxyFactory;
import com.xx.service.ProductService;
import com.xx.service.impl.ProductServiceBean;
public class TestProduct {
@BeforeClass
public static void setUpBeforeClass() throws Exception {
}
@Test
public void testGet(){
ProductService productService = (ProductService)new ProxyFactory().getPropxy(new ProductServiceBean());
productService.get();
}
}