You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Spring Data JPA项目配置Github Actions CI遇数据库连接问题求助

解决Github Actions中Spring Boot JPA项目的数据库依赖问题

方案一:使用内存数据库规避真实数据库依赖

如果你的CI构建主要是跑单元测试或集成测试,完全可以用H2这类内存数据库替代真实数据库,无需额外配置服务容器:

  1. 添加H2依赖
    在Maven的pom.xml中添加test scope的H2依赖:

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

    若用Gradle,在build.gradle中添加:

    testImplementation 'com.h2database:h2'
    
  2. 创建测试环境配置文件
    在src/test/resources下新建application-test.properties,配置H2连接信息:

    spring.datasource.url=jdbc:h2:mem:testdb;DB_CLOSE_DELAY=-1
    spring.datasource.driver-class-name=org.h2.Driver
    spring.datasource.username=sa
    spring.datasource.password=
    spring.jpa.hibernate.ddl-auto=create-drop
    spring.jpa.show-sql=true
    
  3. 在Github Actions中激活测试Profile
    在你的Workflow文件(如.github/workflows/ci.yml)里,运行测试/构建命令时指定激活test profile:

    steps:
      - uses: actions/checkout@v4
      - name: Set up JDK 17
        uses: actions/setup-java@v4
        with:
          java-version: '17'
          distribution: 'temurin'
      - name: Run tests with Maven
        run: mvn clean test -Dspring.profiles.active=test
    

方案二:正确配置Github Actions中的Postgres服务容器

如果你必须用真实Postgres数据库,之前连接失败大概率是配置不匹配,以下是正确的配置流程:

  1. 在Workflow中定义Postgres服务
    在Workflow文件中添加Postgres服务,配置好用户名、密码、数据库名,并开启健康检查确保容器就绪:

    services:
      postgres:
        image: postgres:14-alpine
        env:
          POSTGRES_USER: test_user
          POSTGRES_PASSWORD: test_pass
          POSTGRES_DB: test_db
        ports:
          - 5432:5432
        options: >-
          --health-cmd pg_isready
          --health-interval 10s
          --health-timeout 5s
          --health-retries 5
    
  2. 同步Spring Boot的数据库配置
    你可以通过两种方式让Spring项目连接到这个容器:

    • 方式一:命令行参数覆盖配置
      在构建命令中直接传入数据库连接参数:
      - name: Build with Maven
        run: |
          mvn clean install \
          -Dspring.datasource.url=jdbc:postgresql://localhost:5432/test_db \
          -Dspring.datasource.username=test_user \
          -Dspring.datasource.password=test_pass \
          -Dspring.jpa.hibernate.ddl-auto=create-drop
      
    • 方式二:使用CI专用配置文件
      在src/main/resources下新建application-ci.properties:
      spring.datasource.url=jdbc:postgresql://localhost:5432/test_db
      spring.datasource.username=test_user
      spring.datasource.password=test_pass
      spring.jpa.hibernate.ddl-auto=create-drop
      
      然后在Workflow中激活ci profile:
      - name: Build with Maven
        run: mvn clean install -Dspring.profiles.active=ci
      

这样配置后,Github Actions中的Postgres容器就能被Spring Boot项目正常访问,解决构建失败的问题。

内容的提问来源于stack exchange,提问作者Jae Hyune Yea

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.20 01:52:43