Gradle第七章:Java構建入門

7.1. Java插件

7.1. The Java plugin

如你所見,Gradle是一個通用工具.它可以通過腳本構建任何你想要實現的東西.真正實現開箱即用. 但前提是你需要在腳本中編寫好代碼才行.
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.

大部分Java項目基本流程都是相似的:編譯源文件,進行單元測試,創建Jar包. 使用Gradle做這些工作不必爲每個工程都編寫代碼.Gradle已經提供了完美的插件來解決這些問題. 插件就是Gradle的擴展,簡而言之就是爲你添加一些非常有用的 默認配置.Gradle自帶了很多插件,並且你也可以很容易的編寫和分享自己的插件. Java plugin作爲其中之一,爲你提供了諸如編譯,測試,打包等一些功能.
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源文件位置.如果你遵循這些默認規則,那麼你無需在你的腳本文件中書寫太多代碼. 當然,Gradle也允許你自定義項目中的一些規則.實際上,由於對Java工程的構建是基於插件的,那麼你也可以完全不用插件自己編寫代碼來進行構建.
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插件的基本用法.
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.

7.2. 一個基本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:

例 7.1. 採用Java插件
Example 7.1. Using the Java plugin

build.gradle

apply plugin: 'java'
					

備註:示例代碼可以在Gralde發行包中的 samples/java/quickstart下找到.
Note: The code for this example can be found at samples/java/quickstart which is in both the binary and source distributions of Gradle.

定義一個Java項目只需如此而已.這將會爲你添加Java插件及其一些內置任務.
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.

添加了哪些任務?

What tasks are available?

你可以運行gradle tasks列出任務列表.這樣便可以看到Java插件爲你添加了哪些任務
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.

標準目錄結構如下:
project
    +build
    +src/main/java
    +src/main/resources
    +src/test/java
    +src/test/resources
Gradle默認會從src/main/java搜尋打包源碼,在src/test/java下搜尋測試源碼. 並且src/main/resources下的所有文件按都會被打包,所有src/test/resources下的文件 都會被添加到類路徑用以執行測試.所有文件都輸出到build下,打包的文件輸出到 build/libs
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.

7.2.1. 構建項目

7.2.1. Building the project

Java插件爲你添加了衆多任務.但是它們只是在你需要構建項目的時候才能發揮作用. 最常用的就是build任務,這會構建整個項目.當你執行 gradle build時,Gralde會編譯並執行單元測試,並且將src/main/*下面class和資源文件打包 
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:

例 7.2. 構建Java項目
Example 7.2. Building a Java project

運行gradle build的輸出結果
Output of 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:

clean

刪除build目錄以及所有構建完成的文件.
Deletes the build directory, removing all built files.

assemble

編譯並打包jar文件,但不會執行單元測試.一些其他插件可能會增強這個任務的功能.例如,如果採用了War插件, 這個任務便會爲你的項目打出War包
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.

check

編譯並測試代碼.一些其他插件也可能會增強這個任務的功能.例如,如果採用了Code-quality插件,這個任務會額外執行Checkstyle 
Compiles and tests your code. Other plugins add more checks to this task. For example, if you use the Code-quality plugin, this task will also run Checkstyle against your source code.

7.2.2. 外部依賴

7.2.2. External dependencies

通常,一個Java項目擁有許多外部依賴.你需要告訴Gradle如何找到並引用這些外部文件. 在Gradle中通常Jar包都存在於倉庫中.倉庫可以用來搜尋依賴或發佈 項目產物.下面是一個採用Maven倉庫的例子.
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 arepository. 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:

例 7.3 添加Maven倉庫
Example 7.3. Adding Maven repository

build.gradle

repositories {
    mavenCentral()
}

添加依賴.這裏聲明瞭編譯期所需依賴commons-collections和測試期所需依賴junit.
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:

例 7.4 添加依賴
Example 7.4. Adding dependencies

build.gradle

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

瞭解更多可參閱第 8&nsbp;章, 依賴管理基礎.
You can find out more in Chapter 8, Dependency Management Basics.

7.2.3. 自定義項目

7.2.3. customizing the project

Java插件爲你的項目添加了衆多默認配置.這些默認值通常對於一個普通項目來說已經足夠了.但如果你覺得不適用修改起來也很簡單. 看下面的例子,我們爲Java項目指定了版本號以及所用的Jdk版本,並且添加一些屬性到mainfest中.
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.

例 7.5. 自定義 MANIFEST.MF
Example 7.5. Customization of MANIFEST.MF

build.gradle

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

都有哪些可用屬性?

What properties are available?

可以執行gradle properties來得到項目的屬性列表. 用這條命令可以看到插件添加的屬性以及默認值.
You can use gradle properties to list the properties of a project. This will allow you to see the properties added by the Java plugin, and their default values.

Java插件添加的都是一些普通任務,如同他們寫在Build文件中一樣.這意味着前面章節展示的機制都可以用來修改這些任務的行爲. 例如,可以設置任務的屬性,添加任務行爲,更改任務依賴,甚至是重寫覆蓋整個任務.在下面的例子中,我們將修改 test任務, 這是一個Test類型任務.讓我們來在它執行時爲它添加一些系統屬性.
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:

例 7.6 爲test添加系統屬性
Example 7.6. Adding a test system property

build.gradle

test {
    systemProperties 'property': 'value'
}

7.2.4. 發佈Jar包

7.2.4. Publishing the JAR file

如何發佈Jar包?你需要告訴Gradle發佈到到哪.在Gradle中Jar包通常被髮布到某個倉庫中. 在下面的例子中,我們會將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.

例 7.7. 發佈Jar包
Example 7.7. Publishing the JAR file

build.gradle

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

執行 gradle uploadArchives以發佈Jar包.
To publish the JAR file, run gradle uploadArchives.

7.2.5. 創建Eclipse文件

7.2.5. Creating an Eclipse project

若要把項目導入Eclipse中,你需要添加另外一個插件到你的腳本文件中.
To import your project into Eclipse, you need to add another plugin to your build file:

例 7.8. Eclipse plugin
Example 7.8. Eclipse plugin

build.gradle

apply plugin: 'eclipse'
						

執行gradle eclipse來生成Eclipse項目文件.瞭解更多內容請參閱 第 38 章, The Eclipse 插件.
Now execute gradle eclipse command to generate Eclipse project files. More on Eclipse task can be found in Chapter 38, The Eclipse Plugin.

7.2.6. 示例彙總

7.2.6. Summary

這是示例代碼彙總得到的一個完整腳本:
Here's the complete build file for our sample:

例 7.9. Java 示例 - 一個完整構建腳本
Example 7.9. Java example - complete build file

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. 多項目構建

7.3. Multi-project Java build

現在來看一個典型的多項目構建的例子.項目結構如下:
Now let's look at a typical multi-project build. Below is the layout for the project:

例 7.10. 多項目構建-項目結構 Example 7.10. Multi-project build - hierarchical layout

Build layout

multiproject/
  api/
  services/webservice/
  shared/

備註: 本示例代碼可在Gradle發行包的samples/java/multiproject位置找到
Note: The code for this example can be found at samples/java/multiproject which is in both the binary and source distributions of Gradle.

此處有三個工程. api 工程用來生成給客戶端用的jar文件,這個jar文件可以爲XML webservice 提供Java客戶端. webservice 是一個web應用,生成 XML. shared 工程包含的是前述兩個工程共用的代碼. 
Here we have three 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 sharedcontains code used both by api and webservice .

7.3.1. 多項目構建定義

7.3.1. Defining a multi-project build

定義一個多項目構建工程需要在根目錄(本例中與multiproject同級)創建一個setting 配置文件來指明構建包含哪些項目.並且這個文件必需叫settings.gradle 本例的配置文件如下:
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:

例 7.11. 多項目構建中的settings.gradle Example 7.11. Multi-project build - settings.gradle file

settings.gradle

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

瞭解更多可參閱第 56 章, 多項目構建.
You can find out more about the settings file in Chapter 56, Multi-project Builds.

7.3.2. 公共配置

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:

例 7.12. 多項目構建-公共配置
Example 7.12. Multi-project build - common configuration

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'
    }
}

值得注意的是我們爲每個子項目都應用了Java插件.這意味着我們在前面章節學習的內容在子項目中也都是可用的. 所以你可以在根項目目錄進行編譯,測試,打包等所有操作.
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.

7.3.3. 工程依賴

7.3.3. Dependencies between projects

同一個構建中可以建立工程依賴,一個工程的jar包可以提供給另外一個工程使用.例如我們可以讓 api工程以依賴於shared工程的jar包. 這樣Gradle在構建api之前總是會先構建shared工程.
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 JAR produced by the shared project. Due to this dependency, Gradle will ensure that project shared always gets built before project api .

例 7.13. 多項目構建-工程依賴
Example 7.13. Multi-project build - dependencies between projects

api/build.gradle

dependencies {
    compile project(':shared')
}
參閱 56.7.1 小節, “停用項目依賴”來了解如何停用此功能.
See Section 56.7.1, “Disabling the build of dependency projects” for how to disable this functionality.

7.3.4. 打包發佈

7.3.4. Creating a distribution

如何發佈,請看下文:
We also add a distribution, that gets shipped to the client:

例 7.14. 多項目構建-發佈
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. 下一步目標?

7.4. Where to next?

本章中,我們瞭解瞭如何構建一個基本Java工程.但這都是一小部分基礎,用Gradle還可以做很多事.關於Java插件想了解更多可參閱 第 23 章, The Java Plugin,並且你可以在Gradle發行包中的 samples/java目錄找到更多例子.
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.

另外,不要忘了繼續閱讀第 8 章, 依賴管理基礎 內容喲~~~
Otherwise, continue on to Chapter 8, Dependency Management Basics.

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章