简体   繁体   中英

How do you create additional jar artifacts from compiled classes using Gradle?

I can't tell if this is a bug with Gradle 1.0m7, or if we are just doing this wrong.

We have some classes that get compiled as apart of a project, that we want to individually jar into it's own artifact. These are for example standalone domain model objects, that we want to share with another project.

I'd prefer not to go the multi-project build route, so how do we tell Gradle to create another jar for these?

Currently we are doing this:

task modelJar(type: Jar) {
    classifier = 'model'
    from fileTree(dir: sourceSets.main.classesDir).matching { include 'com/foo/bar/model/**' }
}

artifacts {
    archives modeljar
}

The issue here, is the modeljar task runs before the classes are compiled. At first we didn't realise this and thought this was working. Turns out, the artifact was picking up classes from the previous run, not the current run. Doing clean before the build results in a jar with no classes in it, and reveals the problem.

I was looking at custom configuration, but it seems pretty complex and I didn't want to overly complicate the build file.

Appreciate any advice.

Thanks.

the most convenient way to do this is

task modelJar(type: Jar) {
    classifier = 'model'
    from sourceSets.main.output
    include 'com/foo/bar/model/**'
}

Some background: sourceSets.main.output is a buildable filecollection. This means that if a task works with this file collection, gradle knows that this file collection must be created before another task can use it. in this particular case, sourcesets.main.classes is wired to the classes task of the java plugin. Therefore you your modelJar task does not need to depend on the classes task explicitly.

How about making modelJar task depend on classes (built-in) task? This should make sure compilation is done before modelJar task.

task modelJar(dependsOn: classes, type: Jar){
  ...

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM