【发布时间】:2016-04-30 21:17:36
【问题描述】:
我正在尝试设置 Spring Boot 以使用多个数据源。我已经按照instructions 设置了两个数据源并将其中一个设置为主要数据源。
@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 数据库运行以打开连接...
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
我在 src/integrationtest/resources 下使用了一个单独的 application.properties 文件,其中包含
spring.jpa.database=H2
如何让我的集成测试将 H2 用于我在运行测试时使用的存储库?
如果我不包含我的自定义数据源,一切似乎都可以正常工作。
谢谢
【问题讨论】:
-
请看我的回答Spring with MyBatis: expected single matching bean but found 2。这可能会有所帮助。这将帮助您在单个应用程序中构建真正的多个数据源。
标签: spring jpa spring-boot spring-jdbc