我試圖設置Spring Boot以使用多個數據源。我按照instructions設置了兩個數據源,並將其中的一個設置爲主數據源。具有多個數據源和內存數據庫的Spring Boot
@Configuration
@EnableJpaRepositories(basePackages={"my.postgres.repositories"}
entityManagerFactoryRef="postgresEntitymanager"
transactionManagerRef="postgresTransactionManager")
public class PgConfig {
@Primary
@Bean(name="postgresDS")
@ConfigurationProperties(prefix="spring.datasource.postgres")
public DataSource postgresDataSource() {
return DataSourceBuilder.create().build();
}
@Primary
@Bean(name="postgresEntityManager")
public LocalContainerEntityManagerFactoryBean postgresEntityManager(EntityManagerFactoryBuilder builder) {
return builder.dataSource(postgresDataSource())
.packages("my.postgres.domain")
.persistenceUnit("postgresPersistenceUnit")
.build();
}
@Primary
@Bean(name = "postgresTransactionManager")
public PlatformTransactionManager postgresTransactionManager(
@Qualifier("postgresEntityManager") EntityManagerFactory entityManagerFactory) {
return new JpaTransactionManager(entityManagerFactory);
}
我有一個oracle的第二個配置類,它缺少@Primary註釋但非常相似。我也將這添加到我的主類以排除數據源自動配置。
@SpringBootApplication(exclude={DataSourceAutoConfiguration.class})
,我現在面臨的問題是這種設置不允許,都應該針對H2 DATABSE運行打開連接我的集成測試...
Caused by: javax.persistence.PersistenceException: org.hibernate.exception.JDBCConnectionException: Could not open connection
Caused by: javax.persistence.PersistenceException: org.hibernate.exception.JDBCConnectionException: Could not open connection
Caused by: org.hibernate.exception.JDBCConnectionException: Could not open connection
Caused by: java.sql.SQLException: The url cannot be null
我使用在其下包含
spring.jpa.database=H2
如何讓我的集成測試使用H2來運行我的測試時,我使用的存儲庫的src/integrationtest /資源單獨application.properties文件?
如果我不包含我的自定義數據源,一切似乎都正常工作。
感謝
請看看我的答案[Spring with MyBatis:預計單個匹配bean,但找到2](http://stackoverflow.com/a/36842458/5619827)。這可能會有所幫助。這將幫助您在單個應用程序中構建真正的多個數據源。 –