Search code examples
javaspringtransactionsspring-integrationpojo

Transaction-aware POJO in Spring Integration


I'm implementing a custom Transformer using a POJO (actually, a POGO) that is basically a text transformation service.

I'd like to make it "aware" of the transaction it belongs to and, at the end of the transaction, invoke a method if the whole transaction succeed and another one if the transaction rollback.

Any hint?

Thanks!


Solution

  • What you need is called TransactionSynchronization. But I'm not sure that you should worry about such a low level and their is would be enough for you just to try...catch the TX stuff.

    Even if it is POJO (or POGO ?) you configure it as a <transformer> (@Transformer) anyway. This kind of component in Spring Integration has <request-handler-advice-chain> (adviceChain) option to insert any Advice implementation around the handleRequestMessage method invocation.

    For your purpose you can do that like this:

    <transformer>
       <request-handler-advice-chain>
           <beans:bean class="org.springframework.integration.handler.advice.ExpressionEvaluatingRequestHandlerAdvice">
                <beans:property name="onSuccessExpression" value=""/>
                <beans:property name="onFailureExpression" value=""/>
           </beans:bean>
           <tx:advice>
               <tx:attributes>
                   <tx:method name="*" />
               </tx:attributes>
           </tx:advice>
       </request-handler-advice-chain>
    </transformer>
    

    Where the TX semantics will be wrapped with that ExpressionEvaluatingRequestHandlerAdvice invoking the desired operation on the TX result, which is based in our case on the fact of Exception on TX rallback.

    More info about <request-handler-advice-chain> you can read from the Reference Manual.