翻译: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),一个源集就是一组被一起编译一起执行的源文件。

原文地址 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

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 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.

目录
相关文章
|
6月前
|
SQL 人工智能 移动开发
Android Studio插件版本与Gradle 版本对应关系
Android Studio插件版本与Gradle 版本对应关系
Android Studio插件版本与Gradle 版本对应关系
|
3月前
|
XML Java 项目管理
java maven 和gradle哪种好
java maven 和gradle哪种好
81 0
|
5月前
|
安全 算法 Java
从零开发基于ASM字节码的Java代码混淆插件XHood
因在公司负责基础框架的开发设计,所以针对框架源代码的保护工作比较重视,之前也加入了一系列保护措施,例如自定义classloader加密保护,授权license保护等,但都是防君子不防小人,安全等级还比较低,经过调研各类加密混淆措施后,决定自研混淆插件,自主可控,能够贴合实际情况进行定制化,达到框架升级后使用零感知,零影响
64 1
从零开发基于ASM字节码的Java代码混淆插件XHood
|
6月前
|
Cloud Native Java Go
解决 Spring Boot 和 Gradle Java 版本兼容性问题:A problem occurred configuring root project ‘demo1‘. > Could n
解决 Spring Boot 和 Gradle Java 版本兼容性问题:A problem occurred configuring root project ‘demo1‘. > Could n
367 0
|
2月前
|
XML 监控 druid
【Java专题_02】springboot+mybatis+pagehelper分页插件+druid数据源详细教程
【Java专题_02】springboot+mybatis+pagehelper分页插件+druid数据源详细教程
|
4月前
|
存储 缓存 Java
Gradle笔记 八 Gradle 插件(二)
Gradle笔记 八 Gradle 插件
57 0
|
4月前
|
Java
Gradle笔记 八 Gradle 插件(一)
Gradle笔记 八 Gradle 插件
77 0
|
5月前
|
Java 开发工具 Maven
burp插件编写 java idea
burp插件编写 java idea
57 0
|
5月前
|
SQL 存储 Java
Java实现excel表数据的批量存储(结合easyexcel插件)
Java实现excel表数据的批量存储(结合easyexcel插件)
|
5月前
|
Java Maven
Java开发必安装的插件Maven Helper
Java开发必安装的插件Maven Helper
40 0