views:

34

answers:

2

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.

+3  A: 

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>
Bozho
yup, you can see the different possibilities here: http://static.springsource.org/spring/docs/3.0.x/spring-framework-reference/html/transaction.html#transaction-declarative
seanizer
+1  A: 

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!

Espen