【问题标题】:Spring Boot with multiple datasources and in memory database具有多个数据源和内存数据库的 Spring Boot
【发布时间】: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 jpa spring-boot spring-jdbc


【解决方案1】:

您可以使用h2 数据库添加自己的测试配置,但在生产中使用其他数据库。您在 spring 应用程序类中排除了DataSourceAutoConfiguration,但它在您的集成测试中很有用。

一个简单的解决方案是仅将不同的 spring 应用程序类用于您的集成测试,而不排除 DataSourceAutoConfiguration 或仅实现您自己的 DataSourceAutoConfiguration 并启用它。您可以决定何时在您自己的实现中启用或不启用您自己的DataSourceAutoConfiguration。例如,如果您的classpath 中存在junitspring-test,它将被启用,否则将被禁用。这要求 junitspring-test 不会包含在生产中,这可以通过依赖管理(例如 maven)来处理。

【讨论】:

    猜你喜欢
    • 2017-04-06
    • 2016-08-27
    • 2014-12-06
    • 1970-01-01
    • 1970-01-01
    • 2018-08-18
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多