Spring启动 - 多个DataSource问题

时间:2015-07-20 19:31:34

标签: spring spring-boot autowired spring-jdbc jdbctemplate

我有一个需要从两个不同的数据库(Oracle和MySQL)获取数据的ReST服务,并在响应中合并这些数据。

我有以下配置。

配置DB 1:

@Configuration 
public class DbConfig_DB1{

    @Bean(name="siebelDataSource")
    public EmbeddedDatabase siebelDataSource(){
        return new EmbeddedDatabaseBuilder().
                setType(EmbeddedDatabaseType.H2).
                addScript("schema.sql").
                addScript("test-data.sql").
                build();

    }

    @Autowired
    @Qualifier("siebelDataSource")
    @Bean(name = "siebelJdbcTemplate") 
    public JdbcTemplate siebelJdbcTemplate(DataSource siebelDataSource) { 
        return new JdbcTemplate(siebelDataSource); 
    } 
}

配置DB2:

@Configuration 
public class DbConfig_DB2{      
    @Bean(name="brmDataSource")
    public EmbeddedDatabase brmDataSource(){
        return new EmbeddedDatabaseBuilder().
                setType(EmbeddedDatabaseType.H2).
                addScript("schema-1.sql").
                addScript("test-data-1.sql").
                build();

    }

    @Autowired
    @Qualifier("brmDataSource")
    @Bean(name = "brmJdbcTemplate") 
    public JdbcTemplate brmJdbcTemplate(DataSource brmDataSource) { 
        return new JdbcTemplate(brmDataSource); 
    } 
} 

数据访问:

@Repository
public class SiebelDataAccess {
    protected final Logger log = LoggerFactory.getLogger(getClass());

    @Autowired
    @Qualifier("siebelJdbcTemplate")
    protected JdbcTemplate jdbc;

    public String getEmpName(Integer id) {

        System.out.println(jdbc.queryForObject("select count(*) from employee", Integer.class));

        Object[] parameters = new Object[] { id };
        String name = jdbc.queryForObject(
                "select name from employee where id = ?", parameters,
                String.class);
        return name;
    }

}

我无法启动应用程序,因为我出现以下错误:

Exception in thread "main" org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'org.springframework.boot.autoconfigure.jdbc.DataSourceTransactionManagerAutoConfiguration': Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: private javax.sql.DataSource org.springframework.boot.autoconfigure.jdbc.DataSourceTransactionManagerAutoConfiguration.dataSource; 

nested exception is org.springframework.beans.factory.NoUniqueBeanDefinitionException: No qualifying bean of type [javax.sql.DataSource] is defined: expected single matching bean but found 2: brmDataSource,siebelDataSource

问题在于上下文中有两个DataSource bean。如何解决这个问题?

1 个答案:

答案 0 :(得分:4)

您可以将其中一个标记为@Primary,以便事务管理器的Spring Boot自动配置知道要选择哪一个。如果您需要管理两者的交易,那么我担心您必须明确设置交易管理。

请参阅Spring Boot documentation

  

创建多个数据源与创建第一个数据源的工作方式相同。如果您使用JDBC或JPA的默认自动配置(那么任何@Autowired注入都将使用它),您可能希望将其中一个标记为@Primary。