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:
@Bean
public PlatformTransactionManager transactionManager(){
return new DataSourceTransactionManager(dataSource());
}
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):
@Transactional
public Response transactions(Request request) {
...
}
Finally, we need to add an annotation to instruct the container to look for the @Transactional annotation:
@Configuration
@EnableTransactionManagement
public class AppConfig { ... }
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)
Simple, Short, straight to the point. my favorite kind of articles thank you.