Thursday, 21 April 2016

How to use Declarative transaction management in Spring ?


1. Define transaction manager beans in Spring XML
<bean id="jotm
  class="org.springframework.transaction.jta.JotmFactoryBean" />

<bean id="txnManager
  class="org.springframework.transaction.jta.JtaTransactionManager">
   <property name="userTransaction">
       <ref local="jotm" />
   </property>
</bean>
Here, we defined a bean named "transactionManager" as Spring transaction manager bean.


2. Define bean on which transaction manager needs to be applied
<bean id="myBean" class="com.genius.MyBean" scope = "prototype">
  <!-- dependency injections here -->
</bean>
It is a normal bean with its dependencies.
Java file MyBean is containing 2 methods : "add" and "delete".


3. Define transaction-proxy bean
<bean id="myTxnBean"  
 class="org.springframework.transaction.interceptor.TransactionProxyFactoryBean">
  <property name="transactionManager" ref="txnManager" />
  <property name="target" ref="myBean" />
  <property name="transactionAttributes">
    <props>
        <prop key="add">
  PROPAGATION_REQUIRED, -java.lang.Exception,-com.shaan.MyException
        </prop>
        <prop key="delete">
  PROPAGATION_REQUIRED, -java.lang.Exception,-com.shaan.MyException
        </prop>
    </props>
  </property>
</bean>

Here, a duplicate bean of myBean (named "myTxnBean") has created with transaction management enabled with it.

In properies, we have provided : 
  1. Transaction manager bean, which is "txnManager".
  2. Target bean on which we have to apply transaction manager. (Here, target is "myBean")
  3. Transaction attributes : Attributes have key and value.
        a. key : Method name on which transaction manager needs to be applied. 
                     ("add" and "delete" methods)
        b. value : Transaction attribute and exception hierarchy. (PROPAGATION_REQUIRED)

Now, We can use both the beans - myBean (without transaction management) and myTxnBean (with transaction management)

No comments:

Post a Comment

Note: only a member of this blog may post a comment.