Java 如何为 Gradle 项目生成类路径?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/20106565/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-12 23:11:38  来源:igfitidea点击:

How do I generate the class path for a Gradle project?

javagradle

提问by Sriram Subramanian

I have a gradle project with multiple packages. After the build, each package generates its jar files in build/libs. The external jar dependencies are pulled into ~/.gradle. I would now like to run the service locally from the commandline with the appropriate classpath. For this purpose, I am writing a script that constructs the classpath. The problem is that the script does not understand all the external dependencies and hence cannot construct the classpath. Is there a way for gradle to help with this? Ideally, I would like to dump all the dependencies into a folder at the end of the build.

我有一个包含多个包的 gradle 项目。构建完成后,每个包都会在 build/libs 中生成它的 jar 文件。外部 jar 依赖项被拉入 ~/.gradle。我现在想从命令行使用适当的类路径在本地运行该服务。为此,我正在编写一个构建类路径的脚本。问题在于脚本不了解所有外部依赖项,因此无法构建类路径。gradle 有没有办法帮助解决这个问题?理想情况下,我想在构建结束时将所有依赖项转储到一个文件夹中。

回答by zagyi

You could try something like this in your build script:

你可以在你的构建脚本中尝试这样的事情:

// add an action to the build task that creates a startup shell script
build << {
    File script = file('start.sh')

    script.withPrintWriter {
        it.println '#!/bin/sh'
        it.println "java -cp ${getRuntimeClasspath()} com.example.Main \"$@\""
    }

    // make it executable
    ant.chmod(file: script.absolutePath, perm: 'u+x')
}

String getRuntimeClasspath() {
    sourceSets.main.runtimeClasspath.collect { it.absolutePath }.join(':')
}

回答by Tom Anderson

Firstly, i would suggest using the application pluginif you can, since it takes care of this already.

首先,如果可以的话,我建议使用应用程序插件,因为它已经解决了这个问题。

If you want to dump the classpath to a file yourself, the simplest way is something like:

如果您想自己将类路径转储到文件中,最简单的方法是:

task writeClasspath << {
    buildDir.mkdirs()
    new File(buildDir, "classpath.txt").text = configurations.runtime.asPath + "\n"
}

If you want to actually copy all the libraries on the classpath into a directory, you can do:

如果要将类路径上的所有库实际复制到目录中,可以执行以下操作:

task copyDependencies(type: Copy) {
    from configurations.runtime
    into new File(buildDir, "dependencies")
}