翻译:Gradle之 Java插件

原文地址 http://www.gradle.org/docs/current/userguide/java_plugin.html

23.1. Usage用法

要使用Java插件,在脚本里加入:

Example 23.1. Using the Java plugin

build.gradle

apply plugin: ‘java‘

23.2. Source sets源集

Java插件引入了一个概念:源集(source set),一个源集就是一组被一起编译一起执行的源文件。这些文件可能包括Java源文件,也可以包括资源文件。有些插件增加了源集包含Groovy和Scala源文件的能力。一个源集具有一个相关的编译路径和运行时路径。

源集的一个作用是将源文件进行逻辑分组来面熟共同的目的。比如可以使用源集定义一个集成测试套件,或用多个源集定义API和实现类。

java插件有两个标准源集:main 和test.。main 源集包含产品源代码,也就是要编译打包成jar的部分。test 源集包含单元测试源代码,编译后用JUnit
或TestNG执行。

23.3. Tasks任务

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 compilecompileTest,
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.
cleanTaskName - 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
compileSourceSetJava All tasks which produce the source set‘s compile classpath. JavaCompile Compiles the given source set‘s Java source files using javac.
processSourceSetResources - Copy Copies the given source set‘s resources into the classes directory.
sourceSetClasses compileSourceSetJava and processSourceSetResources.
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.
buildConfigurationName 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.
uploadConfigurationName 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.

下图是任务间的关系:

Figure 23.1. Java plugin - tasks

23.4. Project layout工程布局

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/sourceSet/java Java source for the given source set
src/sourceSet/resources Resources for the given source set

23.4.1. Changing the project layout改变工程布局

可以通过配置合适的源集来配置布局。后面还会详细讨论,下面是一个简单的例子修改了main中的 Java 和resource source 目录.

Example 23.2. Custom Java source layout

build.gradle

sourceSets {
    main {
        java {
            srcDir ‘src/java‘
        }
        resources {
            srcDir ‘src/resources‘
        }
    }
}

23.5. Dependency management依赖管理

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.

Figure 23.2. Java plugin - dependency configurations

对于加入工程的每个源集,Java插件增加如下依赖配置:

Table 23.6. Java plugin - source set dependency configurations

Name Extends Used by tasks Meaning
sourceSetCompile - compileSourceSetJava Compile time dependencies for the given source set
sourceSetRuntime sourceSetCompile - Runtime time dependencies for the given source set

23.6. Convention properties传统属性

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) buildDir/reportsDirName 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) buildDir/testResultsDirName 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) reportsDir/testReportDirName 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) buildDir/libsDirName 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) buildDir/distsDirName 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) buildDir/docsDirName 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) buildDir/dependencyCacheDirName 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.
sourceCompatibility Java version to generate classes for.
archivesBaseName String projectName 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.

这些属性来自传统对象:JavaPluginConventionBasePluginConvention 和 ReportingBasePluginConvention.

23.7. Working with source sets使用源集

通过 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‘
        }
    }
}

23.7.1. Source set properties源集属性

下面是一些常用的重要的属性,更多的参见: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 buildDir/classes/name The directory to generate the classes of this source set into.
output.resourcesDir File buildDir/resources/name The directory to generate the resources of this source set into.
compileClasspath FileCollection compileSourceSet configuration. The classpath to use when compiling the source files of this source set.
runtimeClasspath FileCollection output + runtimeSourceSetconfiguration. 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”
.
[projectDir/src/name/java] 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”
.
[projectDir/src/name/resources] 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.

23.7.2. Defining new source sets新建源集

在 sourceSets
{ }
 块中命名就可以创建源集了:

Example 23.5. Defining a source set

build.gradle

sourceSets {
    intTest
}

新建源集后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
 来编译

Example 23.7. Compiling a source set

Output of gradle
intTestClasses

> gradle intTestClasses
:compileIntTestJava
:processIntTestResources
:intTestClasses

BUILD SUCCESSFUL

Total time: 1 secs

23.8. Javadoc

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 docsDir/javadoc
title String The name and version of the project

23.9. Clean

clean 任务是Delete的实例,它会把 dir 属性值对应的目录删掉.

Table 23.11. Java plugin - Clean properties

Task Property Type Default Value
dir File buildDir

23.10. Resources资源

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”
.
sourceSet.resources
destinationDir File. Can
set using anything described in Section 16.1,
“Locating files”
.
sourceSet.output.resourcesDir

23.11. CompileJava编译

Java插件会给工程中的每个源集增加一个 JavaCompile 类型实例。主要的配置选项如下:

Table 23.13. Java plugin - Compile properties

Task Property Type Default Value
classpath FileCollection sourceSet.compileClasspath
source FileTree.
Can set using anything described in Section 16.5,
“Specifying a set of input files”
.
sourceSet.java
destinationDir File. sourceSet.output.classesDir

编译任务委托了Ant的 javac 任务,将options.useAnt设为false可以激活Grass的编译集成从而绕过Ant的任务。以后这会成为默认任务。

默认Java的编译工作在Gradle进程中执行。将options.fork 设为 true 会生成单独的进程。在Ant中这样做会减慢编译速度,而在Gradle中相反,Gradle会尽量重复使用编译进程。优先尊重的选项是options.forkOptions

23.13. Jar打包

jar任务会生成jar文件,包括了工程的类文件和资源文件。jar文件是 archives 依赖配置的产出,所以依赖工程可以直接引用。如果要把工程上传到库,jar文件会被声明为依赖描述符的一部分。更多请阅读 Section 16.8,
“Creating archives”
 和 Chapter 51, Publishing
artifacts
.

23.13.1. Manifest主配置清单

每个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")

23.14. Uploading上传

上传请看 Chapter 51, Publishing
artifacts
.

时间: 2024-10-13 11:17:34

翻译:Gradle之 Java插件的相关文章

Gradle 笔记——Java构建入门

Gradle是一个通用的构建工具,通过它的构建脚本你可以构建任何你想要实现的东西,不过前提是你需要先写好构建脚本的代码.而大部分的项目,它们的构建流程基本是一样的,我们不必为每一个工程都编写它的构建代码,因为Gradle已经为我们提供了相应的插件.Gradle 本身自带了许多插件,而对于Gradle没有的插件,可以去github上看看有没有其他人实现,或自己实现.对Java项目而言,Gradle有Java插件,提供了像编译.测试.打包之类的功能. 这里简单介绍一下Java插件. Java插件为构

Gradle 1.12用户指南翻译——第二十三章. Java 插件

其他章节的翻译请参见: http://blog.csdn.net/column/details/gradle-translation.html 翻译项目请关注Github上的地址: https://github.com/msdx/gradledoc/tree/1.12. 直接浏览双语版的文档请访问: http://gradledoc.qiniudn.com/1.12/userguide/userguide.html. 另外,Android 手机用户可通过我写的一个程序浏览文档,带缓存功能的,兼容

Gradle构建Java Web应用:Servlet依赖与Tomcat插件(转)

Gradle的官方tutorial介绍了构建Java Web应用的基本方法.不过在使用Servlet做上传的时候会碰到问题.这里分享下如何通过Servlet上传文件,以及如何使用Gradle来构建相应的Java Web工程. 参考原文:How to Build Web Scanning Application with Gradle Servlet文件上传 使用Servlet文件上传,可以参考Oracle的官方文档The fileupload Example Application.这里需要注意

Gradle用户指南(章7:java插件)

Java插件 如我们所见,gradle是一个通用的构建工具.它可以构建你关心并实现的构建脚本.它是开箱即用的,然而,它不会构建任何东西除非你在你的构建脚本中添加代码. 大多数java项目都有非常相似的基础操作:编译java源文件,运行单元测试,和创建包含类文件的jar包.如果你不想为每个项目添加这些操作代码,那是非常好的.Gradle用插件解决这个问题.这个插件通常通过以某种方式配置你的项目来扩展它,通过添加一系列预配置的任务来做一些有用的东西.Gradle附带大量的附件,当然,你也可以编写自己

Gradle构建Java Web应用:Servlet依赖与Tomcat插件

Gradle的官方tutorial介绍了构建Java Web应用的基本方法.不过在使用Servlet做上传的时候会碰到问题.这里分享下如何通过Servlet上传文件,以及如何使用Gradle来构建相应的Java Web工程. 参考原文:How to Build Web Scanning Application with Gradle Servlet文件上传 使用Servlet文件上传,可以参考Oracle的官方文档The fileupload Example Application.这里需要注意

Gradle构建Java Web应用(转)

转自:http://www.blogjava.net/jiangshachina/archive/2014/02/03/409285.html 本文是发布在java.net上的一篇摘自于<Gradle in Action>一书中的节选,介绍了使用Gradle构建Java Web应用的过程.刚刚接触Gradle,看到了这篇小文,随手译了出来:-) (2014.01.23最后更新) 当今世界,一派繁忙.在职业生涯和私人生活中,我们中间的许多人要同时管理多个项目.你可能常常发现自己处于不知所措及失控

使用 Gradle 构建 Java 项目

使用 Gradle 构建 Java 项目 这个手册将通过一个简单的 Java 项目向大家介绍如何使用 Gradle 构建 Java 项目. 我们将要做什么? 我们将在这篇文档航中创建一个简单的 Java 项目,然后使用 Gradle 构建它. 需要准备什么? 预留15分钟空闲时间 一件称手的兵器(你最喜欢的 IDE 或者文本编辑器) Java环境([JDK6](http://www.oracle.com/technetwork/java/javase/downloads/index.html”J

Gradle自己定义插件

Gradle自己定义插件 在Gradle中创建自己定义插件,Gradle提供了三种方式: 在build.gradle脚本中直接使用 在buildSrc中使用 在独立Module中使用 开发Gradle插件能够在IDEA中进行开发.也能够在Android Studio中进行开发,它们唯一的不同,就是IDEA提供了Gradle开发的插件,比較方便创建文件和文件夹,而Android Studio中,开发人员须要手动创建(但实际上.这些文件夹并不多,也不复杂,全然能够手动创建). 在项目中使用 在And

gradle打包java项目

转载地址:http://www.gfzj.us/series/gradle/2014/12/12/gradle%E5%B0%8F%E7%B3%BB%E5%88%97(4)--gradle%E6%89%93%E5%8C%85java%E9%A1%B9%E7%9B%AE.html 以gradle小系列所举例子为示例,在此处介绍两种gradle发布java项目的方法: fat jar方式 该种方法将工程所依赖的jar包等资源都会打到一个可执行jar包中,生成的jar包很大. 在GradleTest项目