`
somefuture
  • 浏览: 1089994 次
  • 性别: Icon_minigender_1
  • 来自: 上海
社区版块
存档分类
最新评论

翻译: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

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.

分享到:
评论

相关推荐

    Gradle构建 Java项目示例

    - **配置Java插件**:在`build.gradle`文件中,首先需要应用Java插件,如`apply plugin: 'java'`,这会为项目提供默认的任务和配置。 - **源代码目录**:Java插件定义了`src/main/java`作为主源代码目录,`src/...

    深入理解Android(一):Gradle详解

    - **高度可扩展性**:Gradle支持插件机制,可以轻松地添加新的功能或集成第三方工具,使得构建过程更加多样化。 #### 四、Gradle的实际应用场景 1. **多版本管理**:通过Gradle的配置文件,可以轻松地定义和管理...

    Android studio 配置gradle 2.2.3 插件所需pom、jar文件

    Maven仓库使用pom文件来管理Java库的依赖,虽然Android Studio主要使用Gradle,但在处理依赖时也会参考pom文件。 配置Android Studio的Gradle插件涉及以下几个步骤: 1. **设置Gradle版本**:在Android Studio中,...

    Gradle资料 java构建项目

    1. **内置插件**:Gradle提供了许多内置插件,如Java插件、War插件,它们提供了一系列预设的任务和配置。 2. **自定义插件**:开发者可以通过编写自己的插件扩展Gradle功能,插件可以封装复杂的构建逻辑。 3. **...

    android-gradle-aspectj:gradle插件在Android项目中添加了对AspectJ的支持

    `android-gradle-aspectj`插件的工作原理是通过在Gradle构建流程中添加额外的步骤,将AspectJ的编译器(ajc)与现有的Java或Kotlin编译过程相结合。这样,我们可以在编写Kotlin或Java代码的同时,编写AspectJ代码,...

    gradle-8.5-all

    3. **编写构建脚本**:在`build.gradle`中定义项目属性、依赖和任务,如`apply plugin: 'java'`应用Java插件,`dependencies`定义依赖库。 4. **执行构建**:使用`gradle build`命令,Gradle会根据脚本执行编译、...

    gradle-6.8.2-all.zip

    Gradle 是一个强大的构建自动化工具,广泛用于Java、Android和其他多语言项目。...同时,其插件体系和DSL语法使定制变得简单,无论是在Java项目还是Android项目中,Gradle都是一个不可或缺的工具。

    gradle-errorprone-plugin:Gradle插件可使用易于出错的Java编译器

    Gradle容易出错的插件该插件将JavaCompile任务配置为使用。要求该插件至少需要使用Gradle 5.2。 虽然支持JDK 8,但建议至少使用JDK 9编译器。 请参阅有关JDK 8支持的。用法plugins { id( " net.ltgt.errorprone " ) ...

    gradle合集之gradle5.5.zip

    5. **插件改进**:Gradle 5.5 对内置的Java、Android等插件进行了更新,提供了更多的配置选项和更好的兼容性。 6. **API稳定性**:Gradle 5.5 确保了核心API的稳定性,这使得开发插件或构建脚本更加可靠,因为这些...

    android-maven-gradle-plugin,与android库项目兼容的gradle的maven插件.zip

    《Android Maven Gradle 插件:与Android库项目兼容的构建工具详解》 在Android开发领域,构建工具的不断更新迭代对于开发者来说既是机遇也是挑战。Android Maven Gradle 插件,作为Android库项目与Maven集成的重要...

    谜题:Gradle插件-混淆器字符串加密(AndroidJava)

    谜 Gradle插件-混淆器字符串加密(Android / ... Gradle插件: : 中等故事: : 如何整合呢? 首先,请确保在您的项目中初始化了SCM,例如Git: $ cd /path/of/your/project/ $ git init $ git add . $ git commit

    android.tools.build:gradle: 2.2.2 源码

    Gradle是一个基于Groovy和Java的开源构建自动化系统,它允许开发者定义项目构建的规则,并通过插件扩展其功能。在Android项目中,`android.tools.build:gradle`是一个专门针对Android开发的Gradle插件,它负责处理...

    gradle-7.1.1-bin.zip

    Gradle 是一个强大的构建自动化工具,广泛用于Java项目,但同时也支持其他编程语言。它的最新稳定版本是7.1.1,这个压缩包"gradle-7.1.1-bin.zip"包含了Gradle运行所需的所有核心组件和库,使得开发者能够在本地环境...

    extra-java-module-info:Gradle 6.4+插件,可将旧版Java库用作模块化Java项目中的Java模块

    Gradle 6.4+插件,可将旧版Java库用作模块化Java项目中的Java模块。 带有Gradle的Java模块 如何使用这个插件 该插件允许您将模块信息添加到没有任何信息的Java库中。 如果这样做的话,可以给它指定一个正确的模块...

    gradle-java-plugin-example01:gradle java插件示例

    使用元插件“java-gradle-plugin”(应用于 build.gradle)的 Gradle Java 插件示例。 插件存档发布到localMaven plugin-consumer/build.gradle 子项目使用插件,可以执行taksk。 build.gradle 到引导插件项目 ...

    gradle-7.2-bin.zip

    4. **插件系统**:Gradle 具有丰富的插件生态,可以轻松扩展功能,如Android插件、Java插件等。 5. **缓存机制**:通过缓存已构建的工件,减少不必要的重复工作。 二、Gradle 7.2 的新特性与改进 1. **性能优化**...

    gradleguide:Gradle 入门指南

    1. **内置插件**:如Java插件、War插件等,提供默认的任务和配置。 2. **应用插件**:`apply plugin: 'com.android.application'`应用Android插件。 3. **自定义插件**:开发者可以编写自己的Gradle插件,扩展构建...

    gradle-resource-bundle:Gradle插件可将CSV转换为Java资源包

    该插件的目的是使用CSV(逗号分隔值)文件作为源,为Java Resource Bundle创建属性文件。 用法 为了使用该插件,请确保将Gradle Resource Bundle插件添加并应用到您的构建脚本中。 buildscript { repositories { ...

    gradle-3.4.1-all 直接下载使用

    Gradle 是一个强大的自动化构建工具,广泛应用于Java、Android等项目的构建管理。Gradle-3.4.1-all是一个包含Gradle完整版本的压缩包,适用于开发者直接下载并使用,以便在项目中集成和管理构建过程。这个版本的...

    gradle-8.0-bin.zip

    6. **命令行界面**:Gradle的命令行界面是与Gradle交互的主要方式之一。8.0版本可能改进了命令行提示、错误处理和用户体验。 7. **Java支持**:Gradle作为Java项目的主要构建工具,会随着Java版本的更新保持兼容性...

Global site tag (gtag.js) - Google Analytics