public class TxHandler implements InvocationHandler {
private Object originalObject;
public Object bind(Object obj) {
this.originalObject = obj;
return Proxy.newProxyInstance(
obj.getClass().getClassLoader(),
obj.getClass().getInterfaces(),
this);
}
public Object invoke(Object proxy, Method method, Object[] args)
throws Throwable {
Object result = null;
UserTransaction tx = null;
try {
tx = (UserTransaction) (new InitialContext().lookup("java/tx"));
result = method.invoke(originalObject, args);
tx.commit();
} catch (Exception ex) {
if (null != tx) {
try {
tx.rollback();
} catch (Exception e) {
}
}
}
} else {
result = method.invoke(originalObject, args);
}
return result;
}
}
这么一堆代码到底能说明有什么好处?下面看看用户如何使用
UserDao userDao = new UserDaoImp();
TxHandler handler = new TxHandler();
UserDao userProxy = handler.bind(userDap);
userProxy.saveUser(user);
CustomerDao custDao = new CustomerDaoImp();
TxHandler handler = new TxHandler();
CustomerDao custProxy = handler.bind(custDao);
custProxy.saveCustomer(customer);
private Object originalObject;
public Object bind(Object obj) {
this.originalObject = obj;
return Proxy.newProxyInstance(
obj.getClass().getClassLoader(),
obj.getClass().getInterfaces(),
this);
}
public Object invoke(Object proxy, Method method, Object[] args)
throws Throwable {
Object result = null;
UserTransaction tx = null;
try {
tx = (UserTransaction) (new InitialContext().lookup("java/tx"));
result = method.invoke(originalObject, args);
tx.commit();
} catch (Exception ex) {
if (null != tx) {
try {
tx.rollback();
} catch (Exception e) {
}
}
}
} else {
result = method.invoke(originalObject, args);
}
return result;
}
}
这么一堆代码到底能说明有什么好处?下面看看用户如何使用
UserDao userDao = new UserDaoImp();
TxHandler handler = new TxHandler();
UserDao userProxy = handler.bind(userDap);
userProxy.saveUser(user);
CustomerDao custDao = new CustomerDaoImp();
TxHandler handler = new TxHandler();
CustomerDao custProxy = handler.bind(custDao);
custProxy.saveCustomer(customer);

浙公网安备 33010602011771号