Controlling inner transaction settings from outer transaction with Spring 2.5

时间秒杀一切 提交于 2019-12-23 13:19:11

问题


I'm using Spring 2.5 transaction management and I have the following set-up:

Bean1

@Transactional(noRollbackFor = { Exception.class })
public void execute() {
  try {
    bean2.execute();
  } catch (Exception e) {
    // persist failure in database (so the transaction shouldn't fail)
    // the exception is not re-thrown
  }
}

Bean2

@Transactional
public void execute() {
  // do something which throws a RuntimeException
}

The failure is never persisted into DB from Bean1 because the whole transaction is rolled back.

I don't want to add noRollbackFor in Bean2 because it's used in a lot of places which don't have logic to handle runtime exceptions properly.

Is there a way to avoid my transaction to be rolled back only when Bean2.execute() is called from Bean1?

Otherwise, I guess my best option is to persist my failure within a new transaction? Anything else clean I can do?


回答1:


This is one of the caveats of annotations... your class is not reusable!

If you'd configure your transactions in the XML, if would have been possible.

Assuming you use XML configuration: if it's not consuming expensive resources, you can create another instance of bean2 for the use of the code you specified. That is, you can configure one been as you specified above, and one with no roll back for exception.



来源:https://stackoverflow.com/questions/3843205/controlling-inner-transaction-settings-from-outer-transaction-with-spring-2-5

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!