}
public class ClassesDaoInterceptor implements MethodInterceptor {
private Object target;
private MyTransaction myTransaction;
public ClassesDaoInterceptor(Object target, MyTransaction myTransaction) {
this.target = target;
this.myTransaction = myTransaction;
}
public Object create() {
Enhancer en = new Enhancer();
en.setSuperclass(target.getClass());
en.setCallback(this);
return en.create();
}
@Override
public Object intercept(Object proxy, Method method, Object[] args,
MethodProxy arg3) throws Throwable {
System.out.println(proxy.getClass().getName());
System.out.println(arg3.getSuperName());
if (method.getName().equals("saveClasses")
|| method.getName().equals("updateClasses")) {
this.myTransaction.beginTransaction();// ֪ͨ
method.invoke(this.target, args);// Ŀ�귽��
this.myTransaction.commit();
} else {
method.invoke(this.target, args);
}
return null;
}
}
public class MyTransaction {
public void beginTransaction(){
System.out.println("开始事务");
}
public void commit(){
System.out.println("提交事务");
}
}
public class ClassesDaoTest {
public static void testSaveClasses(){
Object dao = new ClassesDaoImpl();
MyTransaction myTransaction = new MyTransaction();
ClassesDaoInterceptor interceptor = new ClassesDaoInterceptor(dao, myTransaction);
ClassesDaoImpl proxyDao= (ClassesDaoImpl) interceptor.create();
Classes classes = new Classes();
classes.setCname("aaaa");
proxyDao.saveClasses(classes);
}
public static void main(String[] args) {
testSaveClasses();
}
}