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

Gradle 自定义Manifest中Class-Path为指定相对路径的配置方法

Gradle 自定义Jar Manifest中Class-Path相对路径配置

写法修正说明

你预想的实现逻辑存在两个语法问题,直接运行会报错:

  • 遍历configurations.runtimeClasspath.files得到的是Java标准File对象,获取文件名的属性是name,不存在fileName属性
  • Groovy语法中反斜杠\是字符串转义字符,要输出字面量反斜杠必须写双反斜杠\\,单写反斜杠会被识别为转义标记触发语法错误

可直接使用的完整配置

替换原有jar任务中Class-Path的取值逻辑即可,完整代码如下:

jar {
    manifest {
        attributes (
            "Main-Class": "x.y.z.main",
            "Specification-Title" : "Oh how specific!",
            "Specification-Vendor" : "Super Secret",
            "Specification-Version" : "1.0", 
            "Implementation-Title" : "Top Notch Software",
            "Implementation-Version" : "1.0 Build Nr. 1",
            "Implementation-Vendor" : "Super Secret",
            "Implementation-Vendor-Id" : "x.y.z.com",
            "Implementation-Url" : "http://www.x.y.z.com",
            // 核心修改:拼接目标相对路径与依赖文件名
            "Class-Path": configurations.runtimeClasspath.files.collect { "libs\\external\\" + it.name }.join(' ')
        )
    }
}

提示:Jar包Manifest的Class-Path规范原生推荐使用正斜杠/作为路径分隔符,跨Windows、Linux、macOS平台兼容性更好,如果没有强制要求使用Windows风格反斜杠路径,可以把路径部分改成"libs/external/${it.name}",不需要额外转义,写法更简洁。

配套依赖拷贝配置(可选)

由于Class-Path指向了Jar包同级的libs/external目录,为了避免运行时找不到依赖类,可以添加自动拷贝依赖的任务,构建时自动把所有运行时依赖复制到对应目录:

task copyRuntimeDependencies(type: Copy) {
    from configurations.runtimeClasspath
    into "${buildDir}/libs/libs/external"
}
// 构建Jar包前自动执行依赖拷贝
jar.dependsOn copyRuntimeDependencies

配置完成后执行build任务,生成的Jar包Manifest中Class-Path就会是你预期的libs\external\依赖包名.jar格式,同时依赖会自动同步到对应路径,直接执行java -jar 生成的jar包名.jar即可正常启动。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.27 21:51:19