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.
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>
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:
@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.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!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With