栀子花开

追求完美

  博客园 :: 首页 :: 新随笔 :: 联系 :: 订阅 :: 管理 ::
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);
posted on 2007-04-27 11:05  杨林  阅读(184)  评论(0)    收藏  举报