In this tutorial, we will learn to apply transactions in any spring application on non-public methods (by deault spring AOP can only advise public methods of beans declared in the IoC container). Using this technique, you can manage transactions for nonpublic methods, or on any methods into objects which are created outside the Spring IoC container (i.e. not managed by IoC container).
Manage transaction using AnnotationTransactionAspect
Spring has an AspectJ aspect named AnnotationTransactionAspect
that can manage transactions for any methods of any objects, even if the methods are non-public or the objects are created outside the Spring IoC container.
This aspect will manage transactions for any methods with the @Transactional
annotation. To enable this useful aspect, you can change configuration in either of two ways given below:
@EnableLoadTimeWeaving
annotation<context:load-time-weaver />
; configuration
Using @EnableLoadTimeWeaving annotation
@EnableLoadTimeWeaving annotation has to be used on your configuration class to picked up at loading time. All you need to do is to define the @EnableTransactionManagement
annotation and set its mode attribute to aspectj.
aspect says that the container should use load-time or compile-time weaving to enable the transaction advice. The other value proxy says that the container should use the default Spring AOP mechanisms.
An example configuration will look like this:
@Configuration @EnableTransactionManagement(mode = AdviceMode.ASPECTJ) @EnableLoadTimeWeaving public class MyApplicationConfiguration { //Configuration code }
Using <context:load-time-weaver /> configuration
If you have used XML based configuration in your application, then you may use below configuration changes to enable this feature.
<beans> <context:load-time-weaver /> <tx:annotation-driven mode="aspectj"/> <!-- Other beans declarations--> </beans>
<dependency> <groupId>org.springframework</groupId> <artifactId>spring-aspects</artifactId> <version>${spring.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-instrument</artifactId> <version>${spring.version}</version> </dependency>
Drop me your questions and comments below.
Happy Learning !!
Reference : http://docs.spring.io/spring/docs/current/spring-framework-reference/html/aop.html#aop-aj-ltw
hello2333
I add the configuration as your post said, but my project cannot run and throws exception as below. How can I solve this problem? Thank you.
Binh Thanh Nguyen
Thanks, nice tip