【Gradle教程】第七章:Java快速入门

7.1. The Java plugin(Java插件)

As we have seen, Gradle is a general-purpose build tool. It can build pretty much anything you care to implement in your build script. Out-of-the-box, however, it doesn't build anything unless you add code to your build script to do so.
<翻译>正如我们所看到的,Gradle是一个多用途的构建工具。它几乎可以构建任何你想在构建脚本中实现的东西。然而不同于传统构建工具的是,除非你在构建脚本中添加代码来完成某件事否则Gradle不会做任何事情。

Most Java projects are pretty similar as far as the basics go: you need to compile your Java source files, run some unit tests, and create a JAR file containing your classes. It would be nice if you didn't have to code all this up for every project. Luckily, you don't have to. Gradle solves this problem through the use of plugins. A plugin is an extension to Gradle which configures your project in some way, typically by adding some pre-configured tasks which together do something useful. Gradle ships with a number of plugins, and you can easily write your own and share them with others. One such plugin is the Java plugin. This plugin adds some tasks to your project which will compile and unit test your Java source code, and bundle it into a JAR file.
<翻译>就基础部分来说,大部分Java项目都十分相似:你需要编译你的Java源码文件,运行一些单元测试并且创建一个JAR文件来包含你的class文件。如果你不需要为每一个项目做这些事情,那将是一件美妙的事情。幸运的是,你真的不需要。Groovy通过使用插件来解决这个问题。插件是Gradle的扩展,它以某种方式配置你的项目,典型的做法是添加一些预先配置好用于做某些有用事情的task。Gradle和许多插件运行在一起,并且你可以很简单地编写你自己的插件并分享给别人。其中一种插件就是Java插件。这个插件添加了许多task到你的项目中,这些task会编译和测试你的Java源码,并且把它打包进JAR文件。

The Java plugin is convention based. This means that the plugin defines default values for many aspects of the project, such as where the Java source files are located. If you follow the convention in your project, you generally don't need to do much in your build script to get a useful build. Gradle allows you to customize your project if you don't want to or cannot follow the convention in some way. In fact, because support for Java projects is implemented as a plugin, you don't have to use the plugin at all to build a Java project, if you don't want to.
<翻译>Java插件是基于约定的。这意味着在项目的许多方面该插件都定了默认值,比如Java源码应该放在哪里。如果你的项目遵守约定,在你的构建脚本中你通常不需要做太多的事情就可以完成一个有用的构建。如果在某些地方你不想或无法遵循这个约定,Gradle允许你定制你的项目。事实上,因为对Java项目的支持是以一个插件的形式来实现的,如果你不想的话,你根本不需要在构建Java项目时使用这个插件。

We have in-depth coverage with many examples about the Java plugin, dependency management and multi-project builds in later chapters. In this chapter we want to give you an initial idea of how to use the Java plugin to build a Java project.
<翻译>在之后的章节中,我们有许多有关Java插件、依赖管理和多项目构建例子的深入探讨。在本章中我们想要给你一个有关如何使用Java插件构建Java项目的初步概念。

7.2. A basic Java project(一个基础的Java项目)

Let's look at a simple example. To use the Java plugin, add the following to your build file:
<翻译>让我们来看一个简单的例子。想要使用Java插件,你需要添加以下内容到你的构建文件中:

Example 7.1. Using the Java plugin(示例7.1. 使用Java插件)

build.gradle

apply plugin: 'java'

Note: The code for this example can be found at samples/java/quickstart which is in both the binary and source distributions of Gradle.
<翻译>注意:这个示例所使用的源码可以在Gradle安装目录下的samples/java/quickstart目录下找到。
This is all you need to define a Java project. This will apply the Java plugin to your project, which adds a number of tasks to your project.
<翻译>这就是所有你定义一个Java项目时所需要做的。这将会应用Java插件到你的项目中,它会添加一些task到你的项目中。

Gradle expects to find your production source code under src/main/java and your test source code under src/test/java. In addition, any files under src/main/resources will be included in the JAR file as resources, and any files under src/test/resources will be included in the classpath used to run the tests. All output files are created under the build directory, with the JAR file ending up in the build/libs directory.
<翻译>Gradle会期望在src/main/java目录下找到你的项目源码,在src/test/java目录下找到测试源码。另外,在src/main/resources目录下的任何文件都会被作为资源文件添加到JAR文件里,在src/test/resources目录下的任何文件都会被添加到classpath中用于运行测试。所有的输出文件都被创建在build目录里,其中JAR文件在build/libs目录里。

What tasks are available?(都有哪些task可以用?)
You can use gradle tasks to list the tasks of a project. This will let you see the tasks that the Java plugin has added to your project.
<翻译>你可以使用gradle task来列出项目的所有task。这将会让你看到Java插件在你的项目中添加的task。

7.2.1. Building the project(构建项目)

The Java plugin adds quite a few tasks to your project. However, there are only a handful of tasks that you will need to use to build the project. The most commonly used task is the build task, which does a full build of the project. When you run gradle build, Gradle will compile and test your code, and create a JAR file containing your main classes and resources:
<翻译>Java插件添加了许多的task到你的项目中。然而,只有少量的task是你需要在项目中使用的。最常用的task是build task,它可以构建完整的项目。当你运行gradle build命令时,Gradle将会编译和测试你的代码,并且创建一个JAR文件来包含你的主要class和资源文件。

Example 7.2. Building a Java project(示例7.2. 构建一个Java项目)

Output of gradle build(运行gradle build命令后输出的内容)

> gradle build
:compileJava
:processResources
:classes
:jar
:assemble
:compileTestJava
:processTestResources
:testClasses
:test
:check
:build

BUILD SUCCESSFUL

Total time: 1 secs


Some other useful tasks are:
<翻译>其他一些有用task:

clean
Deletes the build directory, removing all built files.
<翻译>删除build目录,移除所有已经构建的文件。

assemble
Compiles and jars your code, but does not run the unit tests. Other plugins add more artifacts to this task. For example, if you use the War plugin, this task will also build the WAR file for your project.
<翻译>编译和打包你的代码,但是不会运行单元测试。其他插件添加进来的更多的artifact到这个task里。例如,如果你使用了War插件,这个task也将会为你的项目构建WAR文件。

check
Compiles and tests your code. Other plugins add more checks to this task. For example, if you use the checkstyle plugin, this task will also run Checkstyle against your source code.
<翻译>编译和测试你的代码。其他插件会添加更多代码检查到该task中。例如,如果你使用checkstyle插件,那么该task也会对你的代码运行Checkstyle。

7.2.2. External dependencies(外部依赖)

Usually, a Java project will have some dependencies on external JAR files. To reference these JAR files in the project, you need to tell Gradle where to find them. In Gradle, artifacts such as JAR files, are located in a repository. A repository can be used for fetching the dependencies of a project, or for publishing the artifacts of a project, or both. For this example, we will use the public Maven repository:
<翻译>通常一个Java项目会依赖一些外部的JAR文件。想要在项目中引用这些JAR文件,你需要告诉Gradle在哪里可以找到这些文件。在Gradle中,artifact(某个项目的产出物,比如JAR文件)是位于一个仓库中。一个仓库可以用来提取项目的依赖文件,或者上传项目的artifact,或是二者一起。作为例子,我们将会使用公共的Maven仓库:

Example 7.3. Adding Maven repository(示例7.3. 添加Maven仓库)

build.gradle

repositories {
    mavenCentral()
}


Let's add some dependencies. Here, we will declare that our production classes have a compile-time dependency on commons collections, and that our test classes have a compile-time dependency on junit:
<翻译>让我们来添加一些依赖。下面的例子里我们会声明我们的class会有一个来自commons collections的编译时依赖,并且我们的test class会有一个来自junit的编译时依赖:

Example 7.4. Adding dependencies(示例7.4. 添加依赖)

build.gradle

dependencies {
    compile group: 'commons-collections', name: 'commons-collections', version: '3.2'
    testCompile group: 'junit', name: 'junit', version: '4.+'
}


You can find out more in Chapter 8, Dependency Management Basics.
<翻译>你可以在第八章,依赖管理基础找到更多详细内容。

7.2.3. Customizing the project(定制项目)

The Java plugin adds a number of properties to your project. These properties have default values which are usually sufficient to get started. It's easy to change these values if they don't suit. Let's look at this for our sample. Here we will specify the version number for our Java project, along with the Java version our source is written in. We also add some attributes to the JAR manifest.
<翻译>Java插件添加了许多的属性到你的项目中。通常情况下这些属性的默认值就能够让你的项目构建起来。如果这些属性值不适合你的项目,那么修改它们也是很容易的。来看下我们的例子是如何实现的。在例子中我们会声明Java项目的版本号,以及我们的源码是用哪个版本的Java编写的。我们还添加了一些JAR manifest属性。

Example 7.5. Customization of MANIFEST.MF(示例 7.5. MANIFEST.MF的定制)

build.gradle

sourceCompatibility = 1.5
version = '1.0'
jar {
    manifest {
        attributes 'Implementation-Title': 'Gradle Quickstart',
                   'Implementation-Version': version
    }
}


The tasks which the Java plugin adds are regular tasks, exactly the same as if they were declared in the build file. This means you can use any of the mechanisms shown in earlier chapters to customize these tasks. For example, you can set the properties of a task, add behaviour to a task, change the dependencies of a task, or replace a task entirely. In our sample, we will configure the test task, which is of type Test, to add a system property when the tests are executed:
<翻译>Java plugin添加的task是有规律的task,确切的就如它们好像是在构建文件中声明的一样。这意味着你可以使用任何在之前文章所示的结构来定义这些task。例如,你可以设置task的属性,添加task的行为,修改task的依赖,或者完全替换掉task。在我们的例子中,我们将会配置test task,它是Test的一种,通过这个方式在运行测试的时候添加一个系统属性:

Example 7.6. Adding a test system property(示例 7.6. 添加一个系统属性)

build.gradle

test {
    systemProperties 'property': 'value'
}


7.2.4. Publishing the JAR file(发布JAR文件)

Usually the JAR file needs to be published somewhere. To do this, you need to tell Gradle where to publish the JAR file. In Gradle, artifacts such as JAR files are published to repositories. In our sample, we will publish to a local directory. You can also publish to a remote location, or multiple locations.
<翻译>通常Jar文件需要发布在某一个地方。想要这么做,你必须告诉Gradle在哪里发布JAR文件。在Gradle里,artifacts(比如JAR文件)被发布到仓库里。在下面的例子中,我们将会发布到一个本地目录。你也可以发布到一个远程地址,或者多个地址。

Example 7.7. Publishing the JAR file(示例 7.7. 发布JAR文件)

build.gradle

uploadArchives {
    repositories {
       flatDir {
           dirs 'repos'
       }
    }
}


To publish the JAR file, run gradle uploadArchives.
<翻译>运行gradle uploadArchives命令来发布JAR文件。

7.2.5. Creating an Eclipse project(创建一个Eclipse项目)

To create the Eclipse-specific descriptor files, like .project, you need to add another plugin to your build file:
<翻译>想要创建Eclipse的项目说明文件,比如.project,你需要添加其他插件到你的构建文件中:

Example 7.8. Eclipse plugin(示例 7.8. Eclipse插件)

build.gradle

apply plugin: 'eclipse'


Now execute gradle eclipse command to generate Eclipse project files. More information about the eclipse task can be found in Chapter 38, The Eclipse Plugin.
<翻译>运行gradle eclipse命令来生成Eclipse项目文件。想要获取更多有关eclipse task的信息可以查阅第38章,Eclipse插件

7.2.6. Summary(总结)

Here's the complete build file for our sample:
<翻译>下面是我们的例子的完整构件文件:

Example 7.9. Java example - complete build file(示例 7.9. Java例子 - 完整的构件文件)

build.gradle

apply plugin: 'java'
apply plugin: 'eclipse'

sourceCompatibility = 1.5
version = '1.0'
jar {
    manifest {
        attributes 'Implementation-Title': 'Gradle Quickstart',
                   'Implementation-Version': version
    }
}

repositories {
    mavenCentral()
}

dependencies {
    compile group: 'commons-collections', name: 'commons-collections', version: '3.2'
    testCompile group: 'junit', name: 'junit', version: '4.+'
}

test {
    systemProperties 'property': 'value'
}

uploadArchives {
    repositories {
       flatDir {
           dirs 'repos'
       }
    }
}


7.3. Multi-project Java build(Java多项目构建)

Now let's look at a typical multi-project build. Below is the layout for the project:
<翻译>让我们来看一个典型的多项目构建。以下是项目的结构:

Example 7.10. Multi-project build - hierarchical layout(示例 7.10. 多项目构建 - 分层布局)

Build layout(构建结构)

multiproject/
  api/
  services/webservice/
  shared/
  services/shared/

Note: The code for this example can be found at samples/java/multiproject which is in both the binary and source distributions of Gradle.
注意:在Gradle安装目录下的samples/java/multiproject目录里可以找到源码。
Here we have four projects. Project api produces a JAR file which is shipped to the client to provide them a Java client for your XML webservice. Project webservice is a webapp which returns XML. Project shared contains code used both by api and webservice. Project services/shared has code that depends on the shared project.
<翻译>在例子中,我们有四个项目。项目api编译出一个JAR文件供webservice使用。项目webservice是一个返回XML文件的webapp。项目shared包含了apiwebservice要用到的代码。项目services/shared/的代码依赖于shared

7.3.1. Defining a multi-project build(定义一个多项目构建)

To define a multi-project build, you need to create a settings file. The settings file lives in the root directory of the source tree, and specifies which projects to include in the build. It must be called settings.gradle. For this example, we are using a simple hierarchical layout. Here is the corresponding settings file:
<翻译>想要定义一个多项目构建,你需要创建一个设置文件。这个设置文件位于项目树的根目录,并且指定哪些项目被包含在构建中。该设置文件必须被命名为settings.gradle。在本例子中,我们使用了一个简单的分层布局。下面有与该层次相一致的设置文件:

Example 7.11. Multi-project build - settings.gradle file(示例 7.11. 多项目构建 - settings.gradle文件)

settings.gradle

include "shared", "api", "services:webservice", "services:shared"


You can find out more about the settings file in Chapter 57, Multi-project Builds.
<翻译>你可以在[第57章, 多项目构建](You can find out more about the settings file in Chapter 57, Multi-project Builds.)中找到更多有关设置文件的信息。

7.3.2. Common configuration(通用配置)

For most multi-project builds, there is some configuration which is common to all projects. In our sample, we will define this common configuration in the root project, using a technique called configuration injection. Here, the root project is like a container and the subprojects method iterates over the elements of this container - the projects in this instance - and injects the specified configuration. This way we can easily define the manifest content for all archives, and some common dependencies:
<翻译>对于大多数多项目构建来说,里面有一些配置对于每一个项目都是通用的。在我们的例子里,我们将会使用一种被称作配置注射技术在根项目里定义通用配置。根项目(多项目构建的根目录)就像一个容器,而subprojects方法会遍历容器内的每一个元素(即子项目)然后将配置信息注入其中。通过这个方式,我们可以很容易地为每一个文件注入配置和一些通用依赖。

Example 7.12. Multi-project build - common configuration(示例 7.12. 多项目构建 - 通用配置)

build.gradle

subprojects {
    apply plugin: 'java'
    apply plugin: 'eclipse-wtp'

    repositories {
       mavenCentral()
    }

    dependencies {
        testCompile 'junit:junit:4.11'
    }

    version = '1.0'

    jar {
        manifest.attributes provider: 'gradle'
    }
}


Notice that our sample applies the Java plugin to each subproject. This means the tasks and configuration properties we have seen in the previous section are available in each subproject. So, you can compile, test, and JAR all the projects by running gradle build from the root project directory.
<翻译>需要注意的是我们的例子里将Java插件应用于每一个子项目。这意味着所有我们在上面看到的task和配置属性在每一个子项目里都是可用的。所以你可以在根目录运行gradle build命令来编译、测试和打包所有的子项目。

Also note that these plugins are only applied within the subprojects section, not at the root level, so the root build will not expect to find Java source files in the root project, only in the subprojects。
<翻译>你还要注意的是这些插件仅仅应用于子项目内部,不包括根目录,所以你不应该该根目录放置任何的Java源文件,只能在子项目里放源文件。

7.3.3. Dependencies between projects(项目间的依赖)

You can add dependencies between projects in the same build, so that, for example, the JAR file of one project is used to compile another project. In the api build file we will add a dependency on the shared project. Due to this dependency, Gradle will ensure that project shared always gets built before project api.
<翻译>你可以在同一个构建之中添加子项目之间的依赖,例如一个项目生成的JAR文件被用来编译另一个项目。在api项目的构件文件里我们将会添加一个shared项目的依赖。由于这个依赖的声明,Gradle将会知道在构建api项目之前必须先构建shared项目。

Example 7.13. Multi-project build - dependencies between projects(示例 7.13. 多项目构建 - 项目间的依赖)

api/build.gradle

dependencies {
    compile project(':shared')
}


See Section 57.7.1, “Disabling the build of dependency projects” for how to disable this functionality.
<翻译>查阅[第57章 7.1节,试项目依赖无效]来了解如何让该功能无效。

7.3.4. Creating a distribution(本章节还没搞懂怎么翻译=。=)

We also add a distribution, that gets shipped to the client:

Example 7.14. Multi-project build - distribution file

api/build.gradle

task dist(type: Zip) {
    dependsOn spiJar
    from 'src/dist'
    into('libs') {
        from spiJar.archivePath
        from configurations.runtime
    }
}

artifacts {
   archives dist
}


7.4. Where to next?(接下来去哪)

In this chapter, you have seen how to do some of the things you commonly need to build a Java based project. This chapter is not exhaustive, and there are many other things you can do with Java projects in Gradle. You can find out more about the Java plugin in Chapter 23, The Java Plugin, and you can find more sample Java projects in the samples/java directory in the Gradle distribution.
<翻译>在本章中,你已经看到了在构建一个基础Java项目时该做的事情。本章内容并不详细,通过Gradle,还有很多其他事情可以在Java项目中做。你可以在第23章,Java插件找到更多有关Java插件的信息,而且你可以在Gradle的安装目录下的samples/java目录中找到更多的Java项目例子。

Otherwise, continue on to Chapter 8, Dependency Management Basics.
<翻译>否则的话,请继续阅读第8章,依赖管理基础

原文地址:http://www.gradle.org/docs/cur ... .html
翻译者:Jerry
邮箱:hjpdyxhjd@163.com

如对翻译内容有异议,请在评论区提出或联系作者
2 分享
ask albertworkhard

要回复文章请先登录注册