2017-02-28 48 views
1

我在1.5.1版本中使用spring引導的應用程序有問題。Spring引導多個數據源

我的應用程序需要使用2個數據庫(Oracle和MySQL的)

我的應用程序使用的數據源2溝通: - MySQL的數據源

@Configuration 
public class OracleDBConfig { 

    @Bean(name = "oracleDb") 
    @ConfigurationProperties(prefix = "spring.ds_oracle") 
    public DataSource oracleDataSource() { 
     return DataSourceBuilder.create().build(); 
    } 

    @Bean(name = "oracleJdbcTemplate") 
    public JdbcTemplate oracleJdbcTemplate(@Qualifier("oracleDb") DataSource dsOracle) { 
     return new JdbcTemplate(dsOracle); 
    } 
} 
  • 的Oracle數據源

    @Configuration 公開課MySQLDBConfig {

    @Bean(name = "mysqlDb") 
        @ConfigurationProperties(prefix = "spring.ds_mysql") 
        public DataSource mysqlDataSource() { 
         return DataSourceBuilder.create().build(); 
        } 
    
        @Bean(name = "mysqlJdbcTemplate") 
        public JdbcTemplate mySQLjdbcTemplate(@Qualifier("mysqlDb")DataSource dsMySQL) { 
         return new JdbcTemplate(dsMySQL); 
        } 
    } 
    

我已經使用前綴在我的applications.properties中定義了2個數據源。

當我啓動程序我有這樣的錯誤:

Parameter 0 of method oracleJdbcTemplate in com.bv.aircraft.config.OracleDBConfig required a single bean, but 2 were found: 
    - mysqlDb: defined by method 'mysqlDataSource' in class path resource [com/bv/aircraft/config/MySQLDBConfig.class] 
    - oracleDb: defined by method 'oracleDataSource' in class path resource [com/bv/aircraft/config/OracleDBConfig.class] 

我曾嘗試使用@Primary但是當我需要使用其他數據源它不工作。

謝謝

+0

什麼是錯誤您收到? –

回答

1

添加在你春天引導配置類以下

@EnableAutoConfiguration(exclude = {DataSourceTransactionManagerAutoConfiguration.class, DataSourceAutoConfiguration.class}) 

用法示例:

@SpringBootApplication 
@EnableAutoConfiguration(exclude = {DataSourceTransactionManagerAutoConfiguration.class, DataSourceAutoConfiguration.class}) 
public class Application { 
    public static void main(String[] args) { 
     SpringApplication.run(Application.class, args); 
    } 
} 
+0

這解決了我的問題!非常感謝 – Ahmed

+0

默認情況下,spring引導啓用DatasourceAutoConfiguration,它初始化DatasourceInitializer以從classpath運行schema.sql和data.sql。這需要您的案例中缺少的單個或主要數據源。因此需要禁用該功能。 – mhshimul

0

或者:

模板配置從數據源配置分離,在這兩個數據源與預選賽進入模板配置注入,或者只是直接調用創建數據源的方法,例如

public JdbcTemplate oracleJdbcTemplate(oracleDataSource()) DataSource dsOracle) { 
    return new JdbcTemplate(dsOracle); 
} 
相關問題