The Java plugin adds Java compilation, testing and bundling capabilities to a project. It serves as the basis for many of the other Gradle plugins.
The Java plugin introduces the concept of a source set. A source set is a group of source files which are compiled and executed together. These source files may include Java source files and resource files. Other plugins add the ability to include Groovy and Scala source files in a source set. A source set has an associated compile classpath, and runtime classpath.
You might use a source set to define an integration test suite, or for the API classes of your project, or to separate source which needs to be compiled against different Java versions.
The Java plugin defines two standard source sets, called main
and test
.
The main
source set contains your production source code, which is compiled and assembled
into a JAR file. The test
source set contains your unit test source code, which is
compiled and executed using JUnit or TestNG.
The Java plugin adds a number of tasks to your project, as shown below.
Table 18.1. Java plugin - tasks
Task name | Depends on | Type | Description |
clean
|
- |
Clean
|
Deletes the project build directory. |
compileJava
|
All tasks which produce the compile classpath. This includes the jar task for
project dependencies included in the compile configuration.
|
Compile
|
Compiles production Java source files using javac. |
processResources
|
- |
Copy
|
Copies production resources into the production classes directory. |
classes
|
compileJava and processResources .
Some plugins add additional compilation tasks.
|
Task
|
Assembles the production classes directory. |
compileTestJava
|
compile , plus all tasks which produce the test compile classpath.
|
Compile
|
Compiles test Java source files using javac. |
processTestResources
|
- |
Copy
|
Copies test resources into the test classes directory. |
testClasses
|
compileTestJava and processTestResources .
Some plugins add additional test compilation tasks.
|
Task
|
Assembles the test classes directory. |
jar
|
compile
|
Jar
|
Assembles the JAR file |
javadoc
|
compile
|
Javadoc
|
Generates API documentation for the production Java source, using Javadoc |
test
|
compile ,
compileTest ,
plus all tasks which produce the test runtime classpath.
|
Test
|
Runs the unit tests using JUnit or TestNG. |
uploadArchives
|
The tasks which produce the artifacts in the archives configuration, including jar .
|
Upload
|
Uploads the artifacts in the archives configuration, including the JAR file. |
For each source set you add to the project, the Java plugin adds the following compilation tasks:
Table 18.2. Java plugin - source set tasks
Task name | Depends on | Type | Description |
compile
|
All tasks which produce the source set's compile classpath. |
Compile
|
Compiles the given source set's Java source files using javac. |
process
|
- |
Copy
|
Copies the given source set's resources into the classes directory. |
|
compile and
process .
Some plugins add additional compilation tasks for the source set.
|
Task
|
Assembles the given source set's classes directory. |
The Java plugin also adds a number of tasks which form a lifecycle for the project:
Table 18.3. Java plugin - lifecycle tasks
Task name | Depends on | Type | Description |
assemble
|
All archive tasks in the project, including jar . Some plugins add additional
archive tasks to the project.
|
Task
|
Assembles all the archives in the project. |
check
|
All verification tasks in the project, including test . Some plugins add
additional verification tasks to the project.
|
Task
|
Performs all verification tasks in the project. |
build
|
check and assemble
|
Task
|
Performs a full build of the project. |
buildNeeded
|
build and build tasks in all project lib dependencies of the
testRuntime configuration.
|
Task
|
Performs a full build of the project and all projects it depends on. |
buildDependents
|
build and build tasks in all projects with a project lib
dependency on this project in a testRuntime configuration.
|
Task
|
Performs a full build of the project and all projects which depend on it. |
build
|
The tasks which produce the artifacts in configuration ConfigurationName .
|
Task
|
Assembles the artifacts in the specified configuration. |
upload
|
The tasks which uploads the artifacts in configuration ConfigurationName .
|
Upload
|
Assembles and uploads the artifacts in the specified configuration. |
The following diagram shows the relationships between these tasks.
The Java plugin assumes the project layout shown below. None of these directories need exist or have anything in them. The Java plugin will compile whatever it finds, and handles anything which is missing.
Table 18.4. Java plugin - default project layout
Directory | Meaning |
src/main/java
|
Production Java source |
src/main/resources
|
Production resources |
src/test/java
|
Test Java source |
src/test/resources
|
Test resources |
src/
|
Java source for the given source set |
src/
|
Resources for the given source set |
You configure the project layout by configuring the appropriate source set. This is discussed in more detail in the following sections. Here is a brief example which changes the main Java and resource source directories.
Example 18.1. Custom Java source layout
build.gradle
sourceSets { main { java { srcDir 'src/java' } resources { srcDir 'src/resources' } } }
The Java plugin adds a number of dependency configurations to your project, as shown below. It assigns
those configurations to tasks such as compileJava
and test
.
To learn more about configurations see Section 28.3.1, “Configurations” and
Section 29.2, “Artifacts and configurations”. Note also that transitive dependencies
are disabled by default for the compile configuration. This can be overridden using:
configurations.compile.transitive = true
Table 18.5. Java plugin - dependency configurations
Name | Extends | Used by tasks | Meaning |
compile | - | compileJava | Compile time dependencies |
runtime | compile | - | Runtime dependencies |
testCompile | compile | compileTestJava | Additional dependencies for compiling tests. |
testRuntime | runtime, testCompile | test | Additional dependencies for running tests only. |
archives | - | uploadArchives | Artifacts (e.g. jars) produced by this project. |
default | runtime, archives | - | Artifacts produced and dependencies required by this project.
|
The Java plugin adds a number of convention properties to the project, shown below. You can use these properties in your build script as though they were properties of the project object (see Section 17.2, “Using the convention object”).
Table 18.6. Java plugin - directory properties
Property name | Type | Default value | Description |
reportsDirName
|
String
|
reports
|
The name of the directory to generate reports into, relative to the build directory. |
reportsDir
|
File (read-only)
|
|
The directory to generate reports into. |
testResultsDirName
|
String
|
test-results
|
The name of the directory to generate test result .xml files into, relative to the build directory. |
testResultsDir
|
File (read-only)
|
|
The directory to generate test result .xml files into. |
testReportDirName
|
String
|
tests
|
The name of the directory to generate the test report into, relative to the reports directory. |
testReportDir
|
File (read-only)
|
|
The directory to generate the test report into. |
libsDirName
|
String
|
libs
|
The name of the directory to generate libraries into, relative to the build directory. |
libsDir
|
File (read-only)
|
|
The directory to generate libraries into. |
distsDirName
|
String
|
dists
|
The name of the directory to generate distributions into, relative to the build directory. |
distsDir
|
File (read-only)
|
|
The directory to generate distributions into. |
docsDirName
|
String
|
docs
|
The name of the directory to generate documentation into, relative to the build directory. |
docsDir
|
File (read-only)
|
|
The directory to generate documentation into. |
dependencyCacheDirName
|
String
|
dependency-cache
|
The name of the directory to use to cache source dependency information, relative to the build directory. |
dependencyCacheDir
|
File (read-only)
|
|
The directory to use to cache source dependency information. |
Table 18.7. Java plugin - other properties
Property name | Type | Default value | Description |
sourceSets
|
SourceSetContainer
(read-only) |
Not null | Contains the project's source sets. |
sourceCompatibility
|
JavaVersion
. Can also set using a String or a Number, eg
'1.5' or 1.5 .
|
1.5
|
Java version compatibility to use when compiling Java source. |
targetCompatibility
|
JavaVersion
. Can also set using a String or Number, eg
'1.5' or 1.5 .
|
|
Java version to generate classes for. |
archivesBaseName
|
String
|
|
The basename to use for archives, such as JAR or ZIP files. |
manifest
|
GradleManifest
|
an empty manifest | The manifest to include in all JAR files. |
metaInf
|
List
|
[]
|
A set of file collections which specify the files to
include in the META-INF directory or all JAR files. |
These properties are provided by convention objects of type
JavaPluginConvention
,
BasePluginConvention
and
ReportingBasePluginConvention
.
You can access the source sets of a project using the sourceSets
property. This
is a container for the project's source sets, of type
SourceSetContainer
.
There is also a sourceSets()
method, which you can pass a closure to which configures the
source set container. The source set container works pretty much the same way as other containers, such
as tasks
.
Example 18.2. Accessing a source set
build.gradle
// Various ways to access the main source set println sourceSets.main.classesDir println sourceSets['main'].classesDir sourceSets { println main.classesDir } sourceSets { main { println classesDir } } // Iterate over the source sets sourceSets.each {SourceSet set -> println set.name }
To configure an existing source set, you simply use one of the above access methods to set the properties of the source set. The properties are described below. Here is an example which configures the main Java and resources directories:
Example 18.3. Configuring the source directories of a source set
build.gradle
sourceSets { main { java { srcDir 'src/java' } resources { srcDir 'src/resources' } } }
To define a new source set, you simply reference it in the sourceSets { }
block.
When you define a source set, the Java plugin adds a number of tasks which assemble the classes for the
source set, as shown in Table 18.2, “Java plugin - source set tasks”. For example, if you add a source set called
intTest
, the Java plugin adds compileIntTestJava
, processIntTestResources
and intTestClasses
tasks.
The following table lists some of the important properties of a source set.
You can find more details in the API documentation for
SourceSet
.
Table 18.8. Java plugin - source set properties
Property name | Type | Default value | Description |
name
|
String (read-only)
|
Not null | The name of the source set, used to identify it. |
classesDir
|
File
|
|
The directory to generate the classes of this source set into. |
compileClasspath
|
FileCollection
|
compile Configuration.
|
The classpath to use when compiling the source files of this source set. |
runtimeClasspath
|
FileCollection
|
classesDir + runtime Configuration.
|
The classpath to use when executing the classes of this source set. |
java
|
SourceDirectorySet
(read-only)
|
Not null |
The Java source files of this source set. Contains only .java files
found in the Java source directories, and excludes all other files.
|
java.srcDirs
|
Set<File> . Can set using anything described in Section 14.4, “Specifying a set of files”.
|
[
|
The source directories containing the Java source files of this source set. |
resources
|
SourceDirectorySet
(read-only)
|
Not null |
The resources of this source set. Contains only resources, and excludes any
.java files found in the resource source directories. Other plugins,
such as the Groovy plugin, exclude additional types of files from this collection.
|
resources.srcDirs
|
Set<File> . Can set using anything described in Section 14.4, “Specifying a set of files”.
|
[
|
The source directories containing the resources of this source set. |
allJava
|
FileTree
(read-only)
|
java
|
All .java files of this source set. Some plugins, such as the Groovy plugin,
add additional Java source files to this collection.
|
allSource
|
FileTree
(read-only)
|
resources + java
|
All source files of this source set. This include all resource files and all Java source files. Some plugins, such as the Groovy plugin, add additional source files to this collection. |
Using dependency configurations to define the source set classpath:
Example 18.5. Defining the classpath of a source set
build.gradle
configurations { intTestCompile { extendsFrom compile } intTestRuntime { extendsFrom intTestCompile, runtime } } sourceSets { intTest { compileClasspath = sourceSets.main.classes + configurations.intTestCompile runtimeClasspath = classes + sourceSets.main.classes + configurations.intTestRuntime } }
Adding a JAR containing the classes of a source set:
Example 18.6. Assembling a JAR for a source set
build.gradle
task intTestJar(type: Jar) { from sourceSets.intTest.classes }
Generating Javadoc for a source set:
Example 18.7. Generating the Javadoc for a source set
build.gradle
task intTestJavadoc(type: Javadoc) { source sourceSets.intTest.allJava }
Adding a test suite to run the tests in a source set:
Example 18.8. Running tests in a source set
build.gradle
task intTest(type: Test) { testClassesDir = sourceSets.intTest.classesDir classpath = sourceSets.intTest.runtimeClasspath }
The javadoc
task is an instance of
Javadoc
.
It supports the core javadoc options and the options of the standard doclet described in the
reference documentation
of the Javadoc executable.
For a complete list of supported Javadoc options consult the API documentation of the following classes:
CoreJavadocOptions
and
StandardJavadocDocletOptions
.
Table 18.9. Java plugin - Javadoc properties
Task Property | Type | Default Value |
classpath
|
FileCollection
|
sourceSets.main.classes + sourceSets.main.compileClasspath
|
source
|
FileTree
. Can set using anything described in Section 14.4, “Specifying a set of files”. |
sourceSets.main.allJava
|
destinationDir
|
File
|
|
title
|
String
|
The name and version of the project |
The clean
task is an instance of
Clean
. It
simply removes the directory denoted by its dir
property.
Table 18.10. Java plugin - Clean properties
Task Property | Type | Default Value |
dir
|
File
|
|
The Java plugin uses the
Copy
task for resource handling. It adds an
instance for each source set in the project. You can find out more about the copy task in
Section 14.5, “Copying files”.
Table 18.11. Java plugin - ProcessResources properties
Task Property | Type | Default Value |
srcDirs
|
Object . Can set using anything described in Section 14.4, “Specifying a set of files”. |
|
destinationDir
|
File . Can set using anything described in Section 14.1, “Locating files”. |
|
The Java plugin adds a
Compile
instance for each
source set in the project. The compile task delegates to Ant's javac task to do the compile. You can set most
of the properties of the Ant javac task.
Table 18.12. Java plugin - Compile properties
Task Property | Type | Default Value |
classpath
|
FileCollection
|
|
source
|
FileTree
. Can set using anything described in Section 14.4, “Specifying a set of files”. |
|
destinationDir
|
File . |
|
The test
task is an instance of
Test
. It
executes all unit tests found in the test
source set.
Table 18.13. Java plugin - test properties
Task Property | Type | Default Value |
testClassesDir
|
File
|
sourceSets.test.classesDir
|
classpath
|
FileCollection
|
sourceSets.test.runtimeClasspath
|
testResultsDir
|
File
|
testResultsDir
|
testReportDir
|
File
|
testReportDir
|
testSrcDirs
|
List<File>
|
sourceSets.test.java.srcDirs
|
Have a look at
Test
for its complete API. Right now the test results are always in XML-format. The task has a
stopAtFailuresOrErrors
property to control the behavior when tests are failing. Test
always
executes all tests. It stops the build afterwards if
stopAtFailuresOrErrors
is true and there are failing tests or tests that have thrown an uncaught exception.
Per default the tests are run in a forked JVM and the fork is done per test. You can modify this behavior by setting forking to false or set the forkmode to once.
The Test task detects which classes are test classes by inspecting the compiled test classes. By default it scans all .class files. You can set custom includes / excludes, only those classes will be scanned. Depending on the Test framework used (JUnit / TestNG) the test class detection uses different criteria.
When using JUnit, we scan for both JUnit 3 and 4 test classes. If any of the following criteria match, the class is considered to be a JUnit test class. Extend TestCase or GroovyTestCase, Class annotated with RunWith or contain a method annotated with Test (inherited test methods are detected).
When using TestNG, we scan for methods annotated with Test (inherited test methods are detected).
Since 0.6.1 we scan up the inheritance tree into jar files on the test classpath.
In case you don't want to use the test class detection, you can disable it by setting scanForTestClasses to false.
This will make the test task only use the includes / excludes to find test classes.
If scanForTestClasses
is disabled and no include or exclude patterns are specified, the
respective defaults are used. For include this is "**/*Tests.class", "**/*Test.class"
and the for exclude it is "**/Abstract*.class"
.
Both JUnit and TestNG are supported through their Ant tasks.
Regarding TestNG reporting, when the test report is disabled the default TestNG listeners are disabled (options.useDefaultListeners is set to false).
The jar
task creates a JAR file containing the class files and resources of the
project. The JAR file is declared as an artifact in the archives
dependency
configuration. This means that the JAR is available in the classpath of a dependent project. If you upload
your project into a repository, this JAR is declared as part of the dependency descriptor. To learn
more about how to work with archives and artifact configurations see Chapter 29, Artifact Management.
If you come from Maven you can have only one library JAR per project. With Gradle you can have as many as you want. You can also add WAR, ZIP and TAR archives to your project. They are all added the same way, so let's look at how you add a ZIP file.
Example 18.9. Creation of ZIP archive
build.gradle
usePlugin 'java' version = 1.0 task myZip(type: Zip) { fileSet(dir: 'somedir') } println myZip.archiveName
Output of gradle -q myZip
> gradle -q myZip zipProject-1.0.zip
This adds a Zip archive task with the name myZip
which produces ZIP file
zipProject-1.0.zip
. It is important to distinguish between the name of the archive task
and the name of the archive generated by the archive task. The name of the generated archive file is by
default the name of the project with the project version appended. The default name for archives can be
changed with the archivesBaseName
project property. The name of the archive can also be
changed at any time later on.
There are a number of properties which you can set on an archive task. You can, for example, change the name of the archive:
Example 18.10. Configuration of archive task - custom archive name
build.gradle
usePlugin 'java' version = 1.0 task myZip(type: Zip) { fileSet(dir: 'somedir') baseName = 'customName' } println myZip.archiveName
Output of gradle -q myZip
> gradle -q myZip customName-1.0.zip
You can further customize the archive names:
Example 18.11. Configuration of archive task - appendix & classifier
build.gradle
usePlugin 'java' archivesBaseName = 'gradle' version = 1.0 task myZip(type: Zip) { appendix = 'wrapper' classifier = 'src' fileSet(dir: 'somedir') } println myZip.archiveName
Output of gradle -q myZip
> gradle -q myZip gradle-wrapper-1.0-src.zip
Often you will want to publish an archive, so that it is usable from another project. This process is described in Chapter 29, Artifact Management
An archive task is a task which produces an archive at execution time. The following archive tasks are available:
Table 18.14. Archive tasks
The following file containers are available:
Table 18.15. File container for archives
Type | Meaning |
FileTree
|
A set of files defined by a common base directory and include/exclude patterns. See Section 14.3, “File trees”. |
ZipFileSet
|
Extends FileSet with additional properties known from Ant's zipfileset task. |
TarFileSet
|
Extends ZipFileSet with additional properties known from Ant's tarfileset task. |
FileCollection
|
An arbitrary collection of files to include in the archive. In contrast to a
FileTree they don't need to have a common base directory. See Section 14.2, “File collections”
for more details.
|
AntDirective
|
An arbitrary Ant resource declaration. |
To learn about all the details have a look at the javadoc of the archive task class or the file container class itself.
The name of the generated archive is assembled from the task properties baseName
,
appendix
, version
, classifier
and
extension
into
.
[15]
The assembled name is accessible via the baseName
-appendix
-version
-classifier
.extension
archiveName
property. The
name
property denotes the name of the task, not the generated archive. An archive
task has also a customName
property. If this property is set, the
archiveName
property returns its value instead of assembling a name out of the
properties mentioned above.
Archives have a destinationDir
property to specify where the generated archive
should be placed. It has also an archivePath
property, which returns a File object
with the absolute path of the generated archive.
To add content to an archive you must add file container to an archive (see Table 18.15, “File container for archives”). You can add as many file containers as you like. They behave pretty much the same as the Ant resources with similar names.
Example 18.12. Adding content to archive - include & exclude
build.gradle
task zipWithFileSet(type: Zip) { fileSet(dir: 'contentDir') { include('**/*.txt') exclude('**/*.gif') } }
You can add arbitrary files to an archive:
Example 18.13. Adding content to archive - arbitrary files
build.gradle
task zipWithFiles(type: Zip) { files('path_to_file1', 'path_to_file2') }
Other examples:
Example 18.14. Adding content to archive - zipFileSet
build.gradle
task zipWithZipFileSet(type: Zip) { zipFileSet(dir: 'contentDir') { include('**/*.txt') exclude('**/*.gif') prefix = 'myprefix' } }
Example 18.15. Creation of TAR archive
build.gradle
task tarWithFileSet(type: Tar) { tarFileSet(dir: 'contentDir') { include('**/*.txt') exclude('**/*.gif') uid = 'myuid' } }
There is also the option to add an arbitrary Ant expression describing an Ant resource.
myZipTask.antDirective { zipgroupfileset(dir: new File(rootDir, 'lib')) }
This is for rather exotic use cases. Usually you should be fine with the file container provided by Gradle.
If you want to merge the content of other archives into the archive to be generated Gradle offers you
two methods. One is merge
:
myZipTask.merge('path1/otherArchive1.zip', 'path2/otherArchive.tar.gz')
This merges the whole content of the archive passed to the merge method into the generated archive. If you need more control which content of the archive should be merged and to what path, you can pass a closure to the merge method:
myZipTask.merge('path1/otherArchive1.zip', 'path2/otherArchive.tar.gz') { include('**/*.txt') exclude('**/*.gif') prefix = 'myprefix' }
Under the hood Gradle scans the extension of the archives to be merged. According to the extension, it
creates a
ZipFileSet
or TarFileSet
. The closure is applied to this newly created file container. There
is another method for merging called mergeGroup
.
myZipTask.mergeGroup('path_to_dir_with_archives') { include('**/*.zip') exclude('**/*.tar.gz') }
With this method you can assign a set of archives to be merged. Those archives have to be located
under the directory you pass as an argument. You can define filters what archives should be included.
They are always included fully and you can't specify a path. If you need this features, you must use the
merge
method.
The convention object of the Java Plugin has a manifest
property pointing to an instance of
GradleManifest
.
With this GradleManifest
object you can define the content of the
MANIFEST.MF
file for all the jar or a war archives in your project.
Example 18.16. Customization of MANIFEST.MF
build.gradle
manifest.mainAttributes("Implementation-Title": "Gradle", "Implementation-Version": version)
You can also define sections of a manifest file.
If a particular archive needs unique entries in its manifest you have to create your own
GradleManifest
instance for it.
Example 18.17. Customization of MANIFEST.MF for a particular archive
build.gradle
manifest.mainAttributes("Implementation-Title": "Gradle", "Implementation-Version": version) myZipTask.manifest = new GradleManifest(manifest.createManifest()) myZipTask.manifest.mainAttributes(mykey: "myvalue")
Passing the common manifest object to the constructor of GradleManifest
add the common manifest values to the task specific manifest instance.
How to upload your archives is described in Chapter 29, Artifact Management.
Gradle comes with a number of tasks for generating eclipse files for your projects.
EclipseClasspath
has a default instance with the name eclipseCp
. It generates a
.classpath
file.
Table 18.16. Java plugin - Eclipse properties
Task Property | Convention Property |
srcDirs | srcDirs + resourcesDirs |
testSrcDirs | testSrcDirs + testResourcesDirs |
outputDirectory | classesDir |
testOutputDirectory | testClassesDir |
classpathLibs | the resolve result for
testRuntime
|
EclipseProject
has a default instance with the name eclipseProject
. It generates a
.project
file.
Table 18.17. Java plugin - Eclipse project properties
Task Property | Convention Property |
name | project.name |
projectType | ProjectType.JAVA |
The java plugin also provides a task called
eclipse
which generates both of the eclipse tasks mentioned above. If you are using the war plugin,
eclipse
also leads to the execution of the
eclipseWtp
task.