Jar-with-some-dependencies

I have a project that builds a jar (not a war). At compile time this jar has dependencies. Some of these dependencies will be met in the runtime environment, others need to be included in the jar. How can I express this in build script?

I tried this:

configurations {
    compile {
        description = 'compile classpath'
        transitive = true
    }
    library {
        extendsFrom compile
    }
}


dependencies {
    compile('x.y.z:lib1:12.0:jdk1.5')
    compile('javax.ejb:ejb-api:3.0')
    compile('log4j:log4j:1.2.14')
    library('x.y.x:lib2:12.0:jdk1.5')
}

jar {
    into('lib') {
        from configurations.library
    }
}

but the dependencies in x.y.x:lib2 cannot be resolved at compile time.

Ok, I had it backwards. This compiles and makes a jar:

configurations {
    library {
        description = 'get added to jar'
        transitive = false
    }
    compile {
        description = 'compile classpath'
        transitive = true
        extendsFrom library
    }

}

dependencies {
    compile('x.y.z:lib1:12.0:jdk1.5')
    compile('javax.ejb:ejb-api:3.0')
    compile('log4j:log4j:1.2.14')
    library('x.y.x:lib2:12.0:jdk1.5')
}

jar {
    into('lib') {
        from configurations.library
    }
}

But it’s not really what I want. I want to ‘unjar’ the classes from the libraries and add them to my jar in the top level directory tree. How would I do that?

Did you try try the Gradle Shadow plugin?

No, I hadn’t. Thanks, looks like it will do the job.

I’ve now tried it and maybe I’ve found an issue. Or maybe I don’t know how the plugin is supposed to work. When running the build from Eclipse, the shadowed jars are found, and its classes are included in the jar that gradle is building, as expected and as I wanted But when I run the same build on a linux server, even though the compile succeeds, the shadowed jars are NOT included in the jar.

What could cause such a scenario? It makes no sense to me.

Found cause. I was using my rpm plugin which only knew to execute Jar, not shadowJar. By making this task depend on ShadowJar, problem solved. The reason why it APPEARED to work in Eclipse was because I’d previously run the shadowJar task, thus the Jar was felt to be upToDate.

1 Like