代码之家  ›  专栏  ›  技术社区  ›  Sebastian Dusza

Spring 4具有2个jdbc连接

  •  0
  • Sebastian Dusza  · 技术社区  · 8 年前

    如何使用Spring4 java配置类配置2个jdbc连接?

    是否应该为这两个连接配置两个事务管理器?

    编辑:

    我只想使用JdbcTemplate,没有JPA,Spring数据。

    1 回复  |  直到 8 年前
        1
  •  1
  •   Sean Carroll    8 年前

    here

    @Configuration
    public class DataSourceConfiguration {
    
        @Bean
        public PlatformTransactionManager firstDataSourceTransactionManager() {
            return new DataSourceTransactionManager(firstDataSource());
        }
    
        @Bean(destroyMethod = "shutdown")
        @Primary
        public DataSource firstDataSource() {
            return new EmbeddedDatabaseBuilder()
                    .setType(EmbeddedDatabaseType.H2)
                    .generateUniqueName(true)
                    .build();
        }
    
        @Bean
        public JdbcTemplate firstJdbcTemplate() {
            return new JdbcTemplate(firstDataSource());
        }
    
        @Bean
        public PlatformTransactionManager secondDataSourceTransactionManager() {
            return new DataSourceTransactionManager(secondDataSource());
        }
    
        @Bean(destroyMethod = "shutdown")
        public DataSource secondDataSource() {
            return new EmbeddedDatabaseBuilder()
                    .setType(EmbeddedDatabaseType.H2)
                    .generateUniqueName(true)
                    .build();
        }
    
        @Bean
        public JdbcTemplate secondJdbcTemplate() {
            return new JdbcTemplate(secondDataSource());
        }
    
    }