Skip to content
TheChatArchiveThe Chat Archive
gpt-3.5-turbo-0125· openaiHugging Face Suzhen/CodeChat

spring 3 bitronix configuration with @Bean

  1. User

    spring 3 bitronix configuration with @Bean

  2. Assistant

    Here is an example of Spring 3 configuration with Bitronix using the @Bean annotation:

    import bitronix.tm.TransactionManagerServices;
    import bitronix.tm.resource.jdbc.PoolingDataSource;
    import org.springframework.context.annotation.Bean;
    import org.springframework.context.annotation.Configuration;
    import org.springframework.jdbc.core.JdbcTemplate;
    
    import javax.sql.DataSource;
    
    @Configuration
    public class BitronixConfiguration {
    
        @Bean(destroyMethod = "close")
        public PoolingDataSource dataSource() {
            PoolingDataSource dataSource = new PoolingDataSource();
            dataSource.setUniqueName("myDataSource");
            dataSource.setMinPoolSize(1);
            dataSource.setMaxPoolSize(5);
            dataSource.setClassName("org.h2.jdbcx.JdbcDataSource");
            dataSource.setDriverProperties("url=jdbc:h2:mem:test");
            dataSource.init();
            return dataSource;
        }
    
        @Bean
        public JdbcTemplate jdbcTemplate(DataSource dataSource) {
            return new JdbcTemplate(dataSource);
        }
    
        @Bean(destroyMethod = "shutdown")
        public bitronix.tm.BitronixTransactionManager transactionManager() {
            return TransactionManagerServices.getTransactionManager();
        }
    }
    

    In this configuration class, we are creating a PoolingDataSource bean for the database connection pool, a JdbcTemplate bean for executing SQL queries, and a BitronixTransactionManager bean for managing transactions.

    Make sure to include the necessary dependencies for Bitronix and Spring in your project's pom.xml file:

    <dependency>
        <groupId>bitronix-btm</groupId>
        <artifactId>btm</artifactId>
        <version>2.1.4</version>
    </dependency>
    
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-jdbc</artifactId>
        <version>3.2.5.RELEASE</version>
    </dependency>
    

    With this configuration, you can now use the dataSource and jdbcTemplate beans in your Spring application to perform database operations with Bitronix transaction management.