DEV Community


Posted on • Updated on

Spring Transaction Management

To support Spring transaction management we need to declare a PlatformTransactionManager bean. The @Bean method should be named transactionManager. It can return a JpaTransactionManager, DataSourceTransactionManager, JmsTransactionManager, JtaTransactionManager, etc:

    public PlatformTransactionManager transactionManager(){
        return new DataSourceTransactionManager(dataSource());
Enter fullscreen mode Exit fullscreen mode

Now, we need to declare the transactional methods, it may be applied at the class level (to all its methods) or in the interface (since Spring 5.0):

    public Response transactions(Request request) {
Enter fullscreen mode Exit fullscreen mode

Finally, we need to add an annotation to instruct the container to look for the @Transactional annotation:

public class AppConfig { ... }
Enter fullscreen mode Exit fullscreen mode

Spring creates proxies for all the classes annotated with @Transactional (using around advice - see Spring AOP). The proxy implements the following behavior:

  • Transaction started before entering the method
  • Commit at the end of the method
  • Rollback if the method throws a RuntimeException

Top comments (1)

amineamami profile image

Simple, Short, straight to the point. my favorite kind of articles thank you.