原文地址 http://www.gradle.org/docs/current/userguide/java_plugin.html
23.1. Usage用法
要使用Java插件,在脚本里加入:
Java插件引入了一个概念:源集(source set),一个源集就是一组被一起编译一起执行的源文件。这些文件可能包括Java源文件,也可以包括资源文件。有些插件增加了源集包含Groovy和Scala源文件的能力。一个源集具有一个相关的编译路径和运行时路径。
源集的一个作用是将源文件进行逻辑分组来面熟共同的目的。比如可以使用源集定义一个集成测试套件,或用多个源集定义API和实现类。
java插件有两个标准源集:main
和test
.。main
源集包含产品源代码,也就是要编译打包成jar的部分。test
源集包含单元测试源代码,编译后用JUnit 或TestNG执行。
Java插件会给你的工程增加下面的任务:
Table 23.1. Java plugin - tasks
Task name | Depends on | Type | Description |
compileJava |
All tasks which produce the compile classpath. This includes the jar task for project dependencies included in thecompile configuration. |
JavaCompile |
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. |
JavaCompile |
Compiles test Java source files using javac. |
processTestResources |
- | Copy |
Copies test resources into the test classes directory. |
testClasses |
compileTestJava andprocessTestResources . 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 thearchives configuration, including jar . |
Upload |
Uploads the artifacts in the archives configuration, including the JAR file. |
clean |
- | Delete |
Deletes the project build directory. |
clean |
- | Delete |
Deletes the output files produced by the specified task. For example cleanJar will delete the JAR file created by the jar task, and cleanTest will delete the test results created by the test task. |
对于你加入工程的每一个源集,Java插件会增加如下编译任务:
Table 23.2. Java plugin - source set tasks
Task name | Depends on | Type | Description |
compile |
All tasks which produce the source set's compile classpath. | JavaCompile |
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. |
Java插件也增加形成工程生命周期的任务:
Table 23.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 thetestRuntime 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 configurationConfigurationName . |
Task |
Assembles the artifacts in the specified configuration. The task is added by the Base plugin which is implicitly applied by the Java plugin. |
upload |
The tasks which uploads the artifacts in configurationConfigurationName . |
Upload |
Assembles and uploads the artifacts in the specified configuration. The task is added by the Base plugin which is implicitly applied by the Java plugin. |
下图是任务间的关系:
Java插件默认你的工程布局如下,任何目录都可以不存在,也可以不包含任何东西。java插件会编译它找到的任何东西,控制任何丢失的。
Table 23.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 |
Java插件有很多依赖配置,它把这些配置非给各个任务,如compileJava
和 test
.
Table 23.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 | - | The default configuration used by a project dependency on this project. Contains the artifacts and dependencies required by this project at runtime. |
对于加入工程的每个源集,Java插件增加如下依赖配置:
Table 23.6. Java plugin - source set dependency configurations
Name | Extends | Used by tasks | Meaning |
sourceSet Compile |
- | compileSourceSet Java |
Compile time dependencies for the given source set |
sourceSet Runtime |
sourceSet Compile |
- | Runtime time dependencies for the given source set |
Java插件有一些传统属性,如下。你可以直接在脚本中使用这些属性,更多参考 Section 21.3, “Conventions”
Table 23.7. 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 |
distributions |
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 23.8. 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, e.g. '1.5' or1.5 . |
Value of the current used JVM | Java version compatibility to use when compiling Java source. |
targetCompatibility |
JavaVersion . Can also set using a String or Number, e.g. '1.5' or1.5 . |
|
Java version to generate classes for. |
archivesBaseName |
String |
|
The basename to use for archives, such as JAR or ZIP files. |
manifest |
Manifest |
an empty manifest | The manifest to include in all JAR files. |
这些属性来自传统对象:JavaPluginConvention
, BasePluginConvention
和 ReportingBasePluginConvention
.
通过 sourceSets
属性访问源集,它是工程盛放源集的容器, SourceSetContainer
类型的。 还有一个基本块 sourceSets { }
,可以使用闭包来配置源集容器。源集容器工作方式和其他容器完全一样,比如任务tasks
.
Example 23.3. Accessing a source set
build.gradle
// Various ways to access the main source set println sourceSets.main.output.classesDir println sourceSets['main'].output.classesDir sourceSets { println main.output.classesDir } sourceSets { main { println output.classesDir } } // Iterate over the source sets sourceSets.all { println name }
要配置容器,只要用上面的任意一个方法设置源集属性值即可。源集的属性下面会描述。先简单看个例子:
Example 23.4. Configuring the source directories of a source set
build.gradle
sourceSets { main { java { srcDir 'src/java' } resources { srcDir 'src/resources' } } }
下面是一些常用的重要的属性,更多的参见:SourceSet
.
Table 23.9. 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. |
output |
SourceSetOutput (read-only) |
Not null | The output files of the source set, containing its compiled classes and resources. |
output.classesDir |
File |
|
The directory to generate the classes of this source set into. |
output.resourcesDir |
File |
|
The directory to generate the resources of this source set into. |
compileClasspath |
FileCollection |
compile configuration. |
The classpath to use when compiling the source files of this source set. |
runtimeClasspath |
FileCollection |
output + 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 16.5, “Specifying a set of input 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 16.5, “Specifying a set of input files”. |
[ |
The source directories containing the resources of this source set. |
allJava |
SourceDirectorySet (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 |
SourceDirectorySet (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. |
在 sourceSets { }
块中命名就可以创建源集了:
新建源集后Java插件会给它增加一些依赖配置,见上文: Table 23.6, “Java plugin - source set dependency configurations”. 你可以用这些配置定义源集的编译和运行时依赖。
Example 23.6. Defining source set dependencies
build.gradle
sourceSets { intTest } dependencies { intTestCompile 'junit:junit:4.11' intTestRuntime 'org.ow2.asm:asm-all:4.0' }
Java插件会增加一些汇编任务给源集,见上文 Table 23.2, “Java plugin - source set tasks”. 比如对于 intTest的源集可以通过执行
gradle intTestClasses
来编译
javadoc任务是
Javadoc
的实例。它支持核心javadoc选项和标准doclet选项(见 reference documentation )。完整信息参考 CoreJavadocOptions
and StandardJavadocDocletOptions
.
Table 23.10. Java plugin - Javadoc properties
Task Property | Type | Default Value |
classpath |
FileCollection |
sourceSets.main.output + sourceSets.main.compileClasspath |
source |
FileTree . Can set using anything described in Section 16.5, “Specifying a set of input files”. |
sourceSets.main.allJava |
destinationDir |
File |
|
title |
String |
The name and version of the project |
clean
任务是Delete
的实例,它会把 dir
属性值对应的目录删掉.
Table 23.11. 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 16.6, “Copying files”.
Table 23.12. Java plugin - ProcessResources properties
Task Property | Type | Default Value |
srcDirs |
Object . Can set using anything described in Section 16.5, “Specifying a set of input files”. |
|
destinationDir |
File . Can set using anything described in Section 16.1, “Locating files”. |
|
Java插件会给工程中的每个源集增加一个 JavaCompile
类型实例。主要的配置选项如下:
Table 23.13. Java plugin - Compile properties
Task Property | Type | Default Value |
classpath |
FileCollection |
|
source |
FileTree . Can set using anything described in Section 16.5, “Specifying a set of input files”. |
|
destinationDir |
File . |
|
编译任务委托了Ant的 javac 任务,将options.useAnt
设为false可以激活Grass的编译集成从而绕过Ant的任务。以后这会成为默认任务。
默认Java的编译工作在Gradle进程中执行。将options.fork
设为 true
会生成单独的进程。在Ant中这样做会减慢编译速度,而在Gradle中相反,Gradle会尽量重复使用编译进程。优先尊重的选项是options.forkOptions
jar任务会生成jar文件,包括了工程的类文件和资源文件。jar文件是
archives
依赖配置的产出,所以依赖工程可以直接引用。如果要把工程上传到库,jar文件会被声明为依赖描述符的一部分。更多请阅读 Section 16.8, “Creating archives” 和 Chapter 51, Publishing artifacts.
每个jar或war对象都有一个 manifest
属性,值为 Manifest
的单独实例。压缩后对应的MANIFEST.MF文件就写入压缩文件中了。
Example 23.15. Customization of MANIFEST.MF
build.gradle
jar { manifest { attributes("Implementation-Title": "Gradle", "Implementation-Version": version) } }
可以创建 Manifest 的独立实例,这样就可以在jar中共享主配信息了。
Example 23.16. Creating a manifest object.
build.gradle
ext.sharedManifest = manifest { attributes("Implementation-Title": "Gradle", "Implementation-Version": version) } task fooJar(type: Jar) { manifest = project.manifest { from sharedManifest } }
Manifest
对象可以随便合并,可以是文件路径也可以是主配引用等等。
Example 23.17. Separate MANIFEST.MF for a particular archive
build.gradle
task barJar(type: Jar) { manifest { attributes key1: 'value1' from sharedManifest, 'src/config/basemanifest.txt' from('src/config/javabasemanifest.txt', 'src/config/libbasemanifest.txt') { eachEntry { details -> if (details.baseValue != details.mergeValue) { details.value = baseValue } if (details.key == 'foo') { details.exclude() } } } } }
Manifest会按照from
语句中的顺序进行合并。如果合并中发现相同的值则保持原来的,可以通过增加eachEntry
动作自定义合并行为,在里面要访问 ManifestMergeDetails
的实例。合并并不是立即执行的,而是在生成jar文件或者调用 writeTo
和 effectiveManifest的时候。要把主配写入硬盘很简单:
Example 23.18. Separate MANIFEST.MF for a particular archive
build.gradle
jar.manifest.writeTo("$buildDir/mymanifest.mf")