How do I generate the class path for a Gradle proj

2020-06-20 05:24发布

问题:

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.

回答1:

Firstly, i would suggest using the application plugin if 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")
}


回答2:

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(':')
}


标签: java gradle