Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Configuration alternative to Spring @Transactional

Is there any configuration based alternative to the @Transactional annotation in Spring?

I want to keep my java classes as free from Spring as possible, i.e. as decoupled as possible from any framework.

like image 809
simon_d Avatar asked Jun 23 '10 07:06

simon_d


2 Answers

Yes, using aop:config and tx:advice. For example:

<aop:config>
    <aop:pointcut id="serviceMethods"
        expression="execution(* com.package.service..*.*(..))" />

    <aop:advisor advice-ref="txAdvice" pointcut-ref="serviceMethods" />
</aop:config>

<tx:advice id="txAdvice" transaction-manager="transactionManager">
    <tx:attributes>
        <tx:method name="*" propagation="REQUIRED" />
    </tx:attributes>
</tx:advice>
like image 158
Bozho Avatar answered Oct 18 '22 20:10

Bozho


An annotation is the best choice for marking that a method should be executed in a transaction. This is recommended for both Spring and EJB 3.

The XML approach requires much more configuration, isn't refactor friendly and you have to see in the configuration if a certain method will be executed in a transaction or not.

Since annotation based transaction support is the preferred choice by most developers and you don't like to use Spring's @Transactional annotation, I will recommend you to use a custom annotation.

Then you have two choices:

  • Let your custom annotation extend Spring's @Transactional and use the <tx:annotation-driven /> element in your Spring configuration. This is easy and only one annotation needs to be updated to remove the Spring dependency.
  • Create an interceptor that executes logic before and after the annotated method. With Spring as the container, you should delegate the transaction handling from the interceptor's before and after advises to your preferred PlatformTransactionManager implementation.

I have written about how you can create an interceptor that adds logic before and after a method marked with an annotation here. And demonstrated which methods you must use on the PlatformTransactionManager here.

I hope this helps!

like image 32
Espen Avatar answered Oct 18 '22 20:10

Espen