java 类的new_java new一个新的类后面接{}有什么用途?

给你个实例来看下好处, 比如 我们处理业务请求的时候, 都是需要事物来控制提交和回滚的, 是不是每次都需要重复的写 try catch 来begin和commit 或者rollback呢

定义一个你需要的接口来规范行为: 无需对它做实现类.public interface TransactionAction {

void execute(ActionEvent event) throws Exception;

}

定义这个规范, 也就是成功提交 失败回滚

public void transactionProcess(TransactionAction action, ActionEvent event)

throws Exception {

UserTransaction ut = null;

try {

ut = Trans.getUserTransaction();

ut.begin();

action.execute(event);

ut.commit();

} catch (Exception ex) {

StringWriter aWriter = new StringWriter();

ex.printStackTrace(new PrintWriter(aWriter));

Log.error(this.getClass(), aWriter.toString());

try {

ut.rollback();

} catch (Exception e) {

throw new SysException(DAOErrorType.DAO_ROLLBACK_ERROR, e);

}

if (ex instanceof NoMessageAppException) {

return;

}

if (ex instanceof PopupAppException || ex instanceof AppException) {

throw ex;

}

AppException appException = new AppException(-1, ex);

if (null != ex.getMessage()) {

appException.setLocalizedErrorMessage(ex.getMessage());

} else {

appException.setLocalizedErrorMessage(StringResource.getStringData(

"MSG_GS_SP_02143", JSFHelper.getRequest()));

}

throw appException;

}

}

业务中使用:

public void next(ActionEvent event) throws Exception {

helper.transactionProcess(new TransactionAction() {

public void execute(ActionEvent event) throws Exception {

//这时候你只需要关注你的业务了, 不需要管事物了.

}

}

}

ActionEvent: 这个参数就是你业务对象了, 如一般BaseFormBean.

2013年1月04日 14:24

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值