I re-read your question several times and am not sure that I fully understand your question. I assume you are executing someCode , and if that fails, you would like to execute myCustomRollback , which has some information about someCode. Therefore, I will try to provide a general answer.
If you want spring to undo some code. It will only rollback, which is rollBackAble, like a jdbc transaction. Suppose you have a method that makes 2 calls.
@Transactional public void doStuff(SomeEntity entity, File file) { persist(entity); customFileService.createOnFileSystem(file); throw new RunTimeException(); }
Thus, the code above will always be rolled back. It will undo the preservation of your entity, but not the creation of your file, as this is not controlled by spring transactions unless you provide them with a specific implementation.
Secondly, spring provides two ways to work with transactions:
- Spring AOP: A proxy is created at runtime that decorates your code with transactional material. If your class is called MyClass, spring will create the class names MyClassProxy, which will contain your code in the transaction code.
- AspectJ: at compile time, your .class file will be adjusted, and the transaction code will be embedded in your method.
The aspect approach seems more difficult to configure, but it is not so much and easier to use. Since everything annotated with @Transactional will be nested (woven) with code. For spring, AOP is not the case. An internal transaction call, such as in spring, will be ignored! As such, aspectJ provides a more intuitive approach.
Return to what I think your question is (the code is only in 1 class):
public void doSomeCode() { Object restCall = initialize(); try { execute(restCall); } catch (CustomException e) { myCustomRollback(restCall; e); } } @Transactional(rollbackFor = CustomException.class) private void execute(Object restCall) throws CustomException {
The above code will only work with AspectJ! . Because you are calling internal method calls that also seem private! AOP at runtime cannot handle this.
So what happens, everything (that rollbackAble) in execution will be undone. And in doStuff you have information about the objects that were used during execution, now you can use in myCustomRollback to manually roll back your REST elements.
Not sure if I answered this question correctly, but I hope this helps someone with a similar problem.