Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 269
codemaven Avatar asked Dec 01 '22 06:12

codemaven


2 Answers

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.

like image 78
Rene Groeschke Avatar answered Dec 04 '22 18:12

Rene Groeschke


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){
  ...
like image 38
rodion Avatar answered Dec 04 '22 17:12

rodion