Home  >  Spring Core

Example of TransactionManagementConfigurer in Spring

By Arvind Rai, March 21, 2013
TransactionManagementConfigurer supports the database connectivity when we are using XML free bean in spring. TransactionManagementConfigurer is the interface of the package org.springframework.transaction.annotation. We need to override the below methods when using org.springframework.transaction.annotation.
   public DataSource dataSource() {
		
     }

     public PlatformTransactionManager txManager() {
         return new DataSourceTransactionManager(dataSource());
     }

      public PlatformTransactionManager annotationDrivenTransactionManager() {
         return txManager();
     }

 
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();
     }
    
}

 


AppTest.java
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,'Ankita')");
			
	}
}
 
POSTED BY
ARVIND RAI
ARVIND RAI
FIND MORE TUTORILAS


©2019 concretepage.com | Privacy Policy | Contact Us