public class UserDaoimpl {this
public void insert() { System.out.println("insert"); } public void delete() { System.out.println("delete"); } public void update() { System.out.println("update"); } public void seach() { System.out.println("search"); }
}代理
public class Transaction {code
public void begin() { System.out.println("begin"); }對象
public void commit() { System.out.println("commit"); }
}接口
public class DaoIntercepter implements MethodInterceptor {get
private Object target; private Transaction transaction; public DaoIntercepter(Object target, Transaction transaction2) { this.target = target; this.transaction = transaction2; } /// 子代理對象 public Object createProxy() { Enhancer enhancer = new Enhancer(); // 設置回調接口 enhancer.setCallback(this); enhancer.setClassLoader(target.getClass().getClassLoader()); enhancer.setInterfaces(target.getClass().getInterfaces()); // 指定子代理的父類 enhancer.setSuperclass(target.getClass()); // 建立子代理對象 return enhancer.create(); } // 接口中的回調方法 public Object intercept(Object arg0, Method method, Object[] arg2, MethodProxy arg3) throws Throwable { String name = method.getName(); if (name.equals("seach")) { method.invoke(target, arg2); } else { transaction.begin(); method.invoke(target, arg2); transaction.commit(); } return null; }
public class CglibTest {it
public void test() { UserDaoimpl userDaoimpl = new UserDaoimpl(); Transaction transaction = new Transaction(); DaoIntercepter daoIntercepter = new DaoIntercepter(userDaoimpl, transaction); UserDaoimpl userDaoimpl1 = (UserDaoimpl) daoIntercepter.createProxy(); userDaoimpl1.insert(); }
}io