You need to enable JavaScript to run this app. 如何基于Gradle任务实现条件依赖,打包含不同JDBC驱动的可执行Jar
优惠活动
大模型
产品
解决方案
定价
更多

如何基于Gradle任务实现条件依赖,打包含不同JDBC驱动的可执行Jar

Gradle 多JDBC驱动独立打包实现方案

可以实现该需求,以下是可直接运行的完整配置方案:

完整build.gradle配置

plugins {
    id 'java'
    id 'com.github.johnrengelman.shadow' version '8.1.1'
}

group = 'com.example'
version = '1.0.0'

sourceCompatibility = '1.8'

// 定义各数据库专属依赖配置
configurations {
    // 每个数据库的配置同时继承实现和运行时依赖,避免依赖缺失
    mysql.extendsFrom implementation, runtimeOnly
    postgres.extendsFrom implementation, runtimeOnly
}

repositories {
    mavenCentral()
}

dependencies {
    // 通用依赖:所有版本jar都会包含
    implementation 'org.apache.commons:commons-dbcp2:2.9.0'
    // 其他通用业务依赖都放在implementation中
    
    // 各数据库专属JDBC驱动:仅对应版本jar会包含
    mysql 'com.mysql:mysql-connector-j:8.0.33'
    postgres 'org.postgresql:postgresql:42.6.0'
}

// 构建MySQL专属可执行jar
task buildMysql(type: ShadowJar) {
    archiveFileName = "jdbc-app-mysql.jar"
    from sourceSets.main.output
    configurations = [configurations.mysql]
    // 合并SPI服务文件,保证JDBC驱动可被正常加载
    mergeServiceFiles()
    // 配置主类,保证jar可执行,请替换为实际业务主类全路径
    manifest {
        attributes 'Main-Class': 'com.example.YourMainClass'
    }
}

// 构建PostgreSQL专属可执行jar
task buildPostgres(type: ShadowJar) {
    archiveFileName = "jdbc-app-postgres.jar"
    from sourceSets.main.output
    configurations = [configurations.postgres]
    mergeServiceFiles()
    manifest {
        attributes 'Main-Class': 'com.example.YourMainClass'
    }
}

配置说明

  • 依赖配置分层:通用业务依赖全部放入implementation,各数据库的JDBC驱动仅添加到对应专属配置中,保证源码完全一致的前提下,仅打包的驱动有差异
  • 依赖完整性处理:专属配置同时继承implementation和runtimeOnly,解决自定义ShadowJar任务依赖不全的问题
  • SPI兼容处理:调用mergeServiceFiles()合并META-INF下的服务注册文件,避免JDBC驱动无法被Java SPI机制识别加载

使用方法

执行对应打包命令即可生成目标jar包:

# 同时生成MySQL和PostgreSQL两个版本的jar
./gradlew buildMysql buildPostgres

生成的jar包位于build/libs目录下,每个jar仅包含对应数据库的JDBC驱动,可直接独立运行。如果需要适配其他数据库,只需新增对应专属配置和打包任务即可。

内容的提问来源于stack exchange,提问作者aarbor

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.18 15:15:02