Spring TransactionManagementConfigurer Example
November 25, 2021
This page will walk through Spring TransactionManagementConfigurer
example.
1. The
TransactionManagementConfigurer
interface is implemented by the configuration class annotated with @Configuration
and @EnableTransactionManagement
. We need to override its annotationDrivenTransactionManager()
method.
2. By using
TransactionManagementConfigurer
, we can explicitly specify the default PlatformTransactionManager
or ReactiveTransactionManager
bean to be used for annotation-driven transaction management, as opposed to the default approach of a by-type lookup.
3. It is useful in the case when there are two
PlatformTransactionManager
or ReactiveTransactionManager
beans in the container.
4. The
TransactionManagementConfigurer
is introduced in Spring 3.1.
5. It is used as following.
@Configuration @EnableTransactionManagement public class AppConfig implements TransactionManagementConfigurer { ------ @Override public PlatformTransactionManager annotationDrivenTransactionManager() { return txManager(); } }
Using TransactionManagementConfigurer
Find the complete example.AppConfig.java
package com.concretepage; import javax.sql.DataSource; import org.apache.commons.dbcp.BasicDataSource; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.jdbc.datasource.DataSourceTransactionManager; import org.springframework.transaction.PlatformTransactionManager; import org.springframework.transaction.annotation.EnableTransactionManagement; import org.springframework.transaction.annotation.TransactionManagementConfigurer; import com.concretepage.persistence.User; @Configuration @EnableTransactionManagement public class AppConfig implements TransactionManagementConfigurer { @Bean public User user() { return new User(); } @Bean public DataSource dataSource() { BasicDataSource bs=new BasicDataSource(); bs.setDriverClassName("org.hibernate.dialect.MySQLDialect"); bs.setUrl("jdbc:mysql://localhost:3306/hibernate"); bs.setUsername("root"); bs.setPassword(""); return bs; } @Bean public PlatformTransactionManager txManager() { return new DataSourceTransactionManager(dataSource()); } @Override public PlatformTransactionManager annotationDrivenTransactionManager() { return txManager(); } }
package com.concretepage; import java.sql.Connection; import java.sql.SQLException; import java.sql.Statement; import javax.sql.DataSource; import org.springframework.context.annotation.AnnotationConfigApplicationContext; public class AppTest { public static void main(String[] args) throws SQLException { AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext(); ctx.register(AppConfig.class); ctx.refresh(); DataSource ds= ctx.getBean(DataSource.class); Connection con=ds.getConnection(); Statement st=con.createStatement(); st.executeUpdate("insert into user values (1,'Aakash')"); } }