If we want to package the output of the new api
source set in our JAR file, we must define a new task ourselves. Gradle doesn't provide some magic to do this for us automatically; luckily, the task itself is very simple:
apply plugin: 'java' archivesBaseName = 'gradle-sample' version = '1.0' sourceSets { api } task apiJar(type: Jar) { appendix = 'api' from sourceSets.api.output } ...
The task apiJar
is a Jar
task. We define the appendix
property that is used to generate the final filename of the JAR file. We use the from()
method to point to the output directory of our api
source set, so all generated output is included in the JAR file. When we run the task apiJar
, a new JAR file gradle-sample-api-1.0.jar
is generated in the build/libs
directory:
$ gradle apiJar :compileApiJava UP-TO-DATE :processApiResources UP-TO-DATE :apiClasses UP-TO-DATE :apiJar BUILD SUCCESSFUL Total time: 2.998 secs
The base name of the JAR file is the project name, which is similar to one for the jar
task. If we look at the contents, we see our compiled ReadWelcomeMessage
class file:
$ jar tvf build/libs/sample-api.jar 0 Tue Mar 13 11:27:10 CET 2012 META-INF/ 25 Tue Mar 13 11:27:10 CET 2012 META-INF/MANIFEST.MF 0 Tue Mar 13 11:17:50 CET 2012 gradle/ 0 Tue Mar 13 11:17:50 CET 2012 gradle/sample/ 182 Tue Mar 13 11:17:50 CET 2012 gradle/sample/ReadWelcomeMessage.class
Note also that we didn't define a task dependency between the tasks apiJar
and apiClasses
, but when we ran the apiJar
task, Gradle automatically ran the apiClasses
task. This happened because we used the sourceSets.api.output
property to define which files needed to be included in the JAR file; Gradle noticed this and determined which task is responsible for creating the content in the sourceSets.api.output
directory. The
apiClasses
task is the task that compiles the Java source files, and processes the resources into the build directory, so Gradle will first invoke the apiClasses
task before the apiJar
task.
3.137.163.197