java - 在 Spring Boot 的同一个 pom.xml 中管理 H2 和 Postgres

标签 java spring postgresql spring-boot h2

我正在使用 Spring Boot 开发一个微服务应用程序。 我的应用程序将使用 Postgres 数据库进行生产配置,并使用 H2 数据库进行 Spring Boot 自动测试。 因此,我的 pom.xml 包括两个依赖项(H2 + Postgres)。我尝试将 H2 依赖项与 tes 范围相关联,并将 Postgres 与运行时相关联,如下所示:

        <dependency>
            <groupId>com.h2database</groupId>
            <artifactId>h2</artifactId>
            <scope>runtime</scope>
        </dependency>
        <dependency>
            <groupId>org.postgresql</groupId>
            <artifactId>postgresql</artifactId>
            <scope>test</scope>
        </dependency>

在运行 mvn test 时,我可以看到 Spring Boot 默认选择的 postgres 数据库在我的单元测试环境中不存在。这就是为什么我更喜欢使用 H2 来运行单元测试的原因。

是否有正确的方法告诉 spring boot 使用 H2 进行测试,否则使用 Postgres?

我不知道使用不同的 application.properties 文件(一个在 src/main/resources 中,另一个在 src/test/resources 中)是否可以解决问题。

最佳答案

你应该知道有多个类路径,例如:

  1. 编译时类路径,
  2. 运行时类路径,
  3. 测试类路径。

当您使用 <scope>runtime</scope> 时,依赖项将在运行时类路径测试类路径中可用,如the documentation所述:

This scope indicates that the dependency is not required for compilation, but is for execution. It is in the runtime and test classpaths, but not the compile classpath.

这意味着即使您正在执行测试,如果您使用 <scope>runtime</scope>,Postgres 仍然会在您的类路径中。 .


您提到的解决方案,通过提供两个单独的 application.properties是正确的选择。

src/main/resources/application.properties内,您可以像这样配置数据源:

spring.datasource.url=jdbc:postgresql://localhost:5432/mydatabase

src/test/resources/application.properties内,您可以像这样配置数据源:

spring.datasource.url=jdbc:h2:mydatabase

如果需要更细粒度的控制,可以使用 Spring 配置文件。例如,您可以使用名为“testdb”的配置文件,然后使用 @ActiveProfiles("testdb") 注释您的测试。 .

现在您可以创建一个名为 application-testdb.properties 的文件并添加设置测试数据库所需的属性。

关于java - 在 Spring Boot 的同一个 pom.xml 中管理 H2 和 Postgres,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56442400/

相关文章:

java - 在MySQL中存储特殊字符

java - Spring Boot 未加载特定配置文件

使用 Maven 构建的 Java Spring Boot Web App(hello world) 运行时无法启动 Tomcat

postgresql - 如何比较 Postgres 中的时差和秒数?

mysql - 将 Django 数据库后端从 MySql 更改为 PostgreSQL

java - JPA 匹配 ManyToMany 关系中的元素子集

java - 在jsp中捕获SQL Raiserror

java - 如何使用 Robolectric 在 Android 中测试菜单

java - ThreadPoolTask​​Executor 优雅关闭

postgresql - 使用 postgresql 查询在多列中搜索非空条件