Gradle入门(3):构建第一个Java项目

Gradle插件通过引入特定领域的约定和任务来构建你的项目。Java插件是Gradle自身装载的一个插件。Java插件提供的基本功能远比源代码编译和打包多。它为你的项目建立了一个标准的项目布局,并确保有意义,有顺序地执行任务。现在,为你的项目创建一个构建脚本并使用Java插件。

使用Java插件

每个Gradle项目都是以创建名字为build.gradle的文件开始的。创建这个文件,然后像下面这样告诉它要使用Java插件:

apply plugin: 'java'

一行代码足够构建你的Java代码,但是Gradle怎么知道去哪里找源文件呢?Java插件引入的约定之一就是源代码的位置。在默认情况下,插件会到 src/main/java 目录下查找。

自动化生成项目结构

但是,我们要手工来创建build.gradle文件与源代码目录吗?显示不是,gradle提供了初始化项目目录的命令init

gradle init --type [java-library | scala-library | groovy-library | basic | pom]

type参数当前只支持以下类型:

    • basic:缺省值,仅仅为我们创建好构建脚本

    • pom:将一个maven构建的项目转换成一个gradle构建的项目。如果pom.xml存在,这个类型值会被自动指定。

    • java-library:初始化创建一个gradle构建的java项目

    • scala-library:初始化创建一个gradle构建的scala项目

    • groovy-library:初始化创建一个gradle构建的groovy项目

这里以创建java项目为例:

wuchao@wuchao-PC:~/workspace/GradleWorkSpace$ gradle init --type java-library

输出信息:

Picked up _JAVA_OPTIONS:   -Dawt.useSystemAAFontSettings=gasp
Starting a Gradle Daemon (subsequent builds will be faster)
:wrapper
:init

BUILD SUCCESSFUL

Total time: 8.483 secs

图显示,gradle构建的完整的java项目结构就完成了。注意,你们还带了包装器的,后面再讲。

Java工程的任务

Java插件在我们的构建中加入了很多任务,我们这篇教程涉及到的任务如下:

    • assemble任务会编译程序中的源代码,并打包生成Jar文件,这个任务不执行单元测试。
    • build任务会执行一个完整的项目构建。
    • clean任务会删除构建目录。
    • compileJava任务会编译程序中的源代码。

我们还可以执行以下命令得到一个可运行任务及其描述的完整列表:

gradle tasks

 输出以下信息:

:tasks

------------------------------------------------------------
All tasks runnable from root project
------------------------------------------------------------

Build tasks
-----------
assemble - Assembles the outputs of this project.
build - Assembles and tests this project.
buildDependents - Assembles and tests this project and all projects that depend on it.
buildNeeded - Assembles and tests this project and all projects it depends on.
classes - Assembles main classes.
clean - Deletes the build directory.
jar - Assembles a jar archive containing the main classes.
testClasses - Assembles test classes.

Build Setup tasks
-----------------
init - Initializes a new Gradle build. [incubating]
wrapper - Generates Gradle wrapper files. [incubating]

Documentation tasks
-------------------
javadoc - Generates Javadoc API documentation for the main source code.

Help tasks
----------
buildEnvironment - Displays all buildscript dependencies declared in root project 'GradleWorkSpace'.
components - Displays the components produced by root project 'GradleWorkSpace'. [incubating]
dependencies - Displays all dependencies declared in root project 'GradleWorkSpace'.
dependencyInsight - Displays the insight into a specific dependency in root project 'GradleWorkSpace'.
dependentComponents - Displays the dependent components of components in root project 'GradleWorkSpace'. [incubating]
help - Displays a help message.
model - Displays the configuration model of root project 'GradleWorkSpace'. [incubating]
projects - Displays the sub-projects of root project 'GradleWorkSpace'.
properties - Displays the properties of root project 'GradleWorkSpace'.
tasks - Displays the tasks runnable from root project 'GradleWorkSpace'.

Verification tasks
------------------
check - Runs all checks.
test - Runs the unit tests.

Rules
-----
Pattern: clean<TaskName>: Cleans the output files of a task.
Pattern: build<ConfigurationName>: Assembles the artifacts of a configuration.
Pattern: upload<ConfigurationName>: Assembles and uploads the artifacts belonging to a configuration.

To see all tasks and more detail, run gradle tasks --all

To see more detail about a task, run gradle help --task <task>

BUILD SUCCESSFUL

Total time: 1.522 secs

构建项目

你可以开始构建项目了。java插件提供的一个任务叫作build。这个build任务会以正确的顺序编译你的源代码,运行测试,组装JAR文件。运行gradle build命令,你应该可以得到类似于下面的输出:

:compileJava UP-TO-DATE
:processResources UP-TO-DATE
:classes UP-TO-DATE
:jar UP-TO-DATE
:assemble UP-TO-DATE
:compileTestJava UP-TO-DATE
:processTestResources UP-TO-DATE
:testClasses UP-TO-DATE
:test UP-TO-DATE
:check UP-TO-DATE
:build UP-TO-DATE

BUILD SUCCESSFUL

Total time: 1.292 secs

每一行输出都代表着java插件提供的一个可执行任务。你也许注意到某些任务被标记为 UP-TO-DATE 消息。这意味着这个任务被跳过了。Gradle的增量式构建支持自动鉴别不需要被运行的任务。特别是在大型的企业级项目中,这个特性是节省时间的好帮手。在上面的例子中,你可以看到有测试任务执行,测试源代码默认的位置为:src/test/java

运行构建后,在项目的根目录下,你会看到有一个build目录,里面包含了构建运行的所有输出,包括class文件,测试报告和JAR文件,还有一些像清单(manifest)一样的对构建有用的临时文件。

:1. 构建输出目录的名字是可配置的属性。2. JAR文件的名字是继承自项目的名字。

运行项目

运行一个Java应用程序是非常简单的。因为项目是通过命令:

$ gradle init --type java-library

创建的,会产生一个java源文件类的示例和一个java测试类的示例,但并没有带有main函数入口的java类。这里我们创建一个测试类src/main/java/Main.java:

public class Main {   
public static final void main(String[] args){ System.out.println("test File"); } }

再重新构建一下:

$ gradle build

下面,我们来运行项目,执行下面的命令:

$ java -cp build/classes/main/ Main

输出如下:

test File

修改项目和插件属性

下面的例子中,你将给项目指定一个版本号,并且指定Java源代码的兼容性。另外,之前你通过java命令运行应用,通过classpath命令行选项 -cp build/classes/main 告诉Java运行时去哪里找class。为了能够从JAR文件启动应用,清单文件MANIFEST.MF需要包含信息头Main-Class。示例(用前面gradle init --type java-library命令生成的build.gradle,在上面添 加配置项):

/*
 * This build file was auto generated by running the Gradle 'init' task
 * by 'fuhd' at '15-10-22 下午8:14' with Gradle 2.7
 *
 * This generated file contains a sample Java project to get you started.
 * For more details take a look at the Java Quickstart chapter in the Gradle
 * user guide available at https://docs.gradle.org/2.7/userguide/tutorial_java_projects.html
 */

// Apply the java plugin to add support for Java
apply plugin: 'java'

version = 0.1
sourceCompatibility = 1.8
jar{
  manifest{
    attributes 'Main-Class':'Main'
  }
}

// In this section you declare where to find the dependencies of your project
repositories {
    // Use 'jcenter' for resolving your dependencies.
    // You can declare any Maven/Ivy/file repository here.
    jcenter()
}

// In this section you declare the dependencies for your production and test code
dependencies {
    // The production code uses the SLF4J logging API at compile time
    compile 'org.slf4j:slf4j-api:1.7.12'

    // Declare the dependency for your favourite test framework you want to use in your tests.
    // TestNG is also supported by the Gradle Test task. Just change the
    // testCompile dependency to testCompile 'org.testng:testng:6.8.1' and add
    // 'test.useTestNG()' to your build script.
    testCompile 'junit:junit:4.12'
}

然后运行

gradle build

 你会看到版本号添加到了JAR文件的名字中。现在名字是java包的名字是以当前目录名为名字,本人当前目录为wuchao@wuchao-PC:~/workspace/GradleWorkSpace$ ,因此build/libs就会有一个名字为GradleWorkSpace- 0.1.jar的包,可以看出版本号也在jar包名字中。现在生成的JAR文件包含了主类头属性,你可以通过下面这条命令运行应用:

$ java -jar build/libs/GradleWorkSpace-0.1.jar

改造遗留项目

和一个遗留系统集成,迁移已有项目的技术栈,或者坚持内部标准或者限制,实在太常见了。构建工具必须足够灵活,可以通过改变默认配置来适应来自外部的限制。

让我们假设你是在一个完全不一样的目录结构下开始这个项目的。你需要把源代码放置在src目录下,而不是 src/main/java 。同样的道理,也适用于改变默认的测试代码目录。另外,你想要让Gradle将输出结果放置在out目录下, 而不是build。下面代码展示了如何让你的构建适应一个定制的项目结构:

/*
 * This build file was auto generated by running the Gradle 'init' task
 * by 'fuhd' at '15-10-22 下午8:14' with Gradle 2.7
 *
 * This generated file contains a sample Java project to get you started.
 * For more details take a look at the Java Quickstart chapter in the Gradle
 * user guide available at https://docs.gradle.org/2.7/userguide/tutorial_java_projects.html
 */

// Apply the java plugin to add support for Java
apply plugin: 'java'

version = 0.1
sourceCompatibility = 1.8
jar{
  manifest{
    attributes 'Main-Class':'Main'
  }
}

sourceSets{
  main{
    java{
      srcDirs = ['src']            //用不同目录的列表代替约定的源代码
    }
  }
  test{
    java{
      srcDirs = ['test']           //用不同目录的列表代替约定的测试代码目录
    }
  }
}

buildDir = 'out'                   //改变项目输出属性(路径)到out目录

// In this section you declare where to find the dependencies of your project
repositories {
    // Use 'jcenter' for resolving your dependencies.
    // You can declare any Maven/Ivy/file repository here.
    jcenter()
}

// In this section you declare the dependencies for your production and test code
dependencies {
    // The production code uses the SLF4J logging API at compile time
    compile 'org.slf4j:slf4j-api:1.7.12'

    // Declare the dependency for your favourite test framework you want to use in your tests.
    // TestNG is also supported by the Gradle Test task. Just change the
    // testCompile dependency to testCompile 'org.testng:testng:6.8.1' and add
    // 'test.useTestNG()' to your build script.
    testCompile 'junit:junit:4.12'
}

配置和使用外部依赖

Gradle如何引用外部库?我们来看看两个DSL配置元素:repositoriesdependencies

定义仓库

在Java世界,依赖都是以JAR文件的形式发布和使用的。许多类库都可以在仓库中找到,仓库可以是一个文件系统或者一个中心服务器。Gradle要求你定义至少一个仓库来使用依赖。为此,你需要使用公共的可访问的仓库Maven Central:

repositories {
    mavenCentral()        //配置对Maven Central2仓库访问的快捷方式 
}

定义好仓库之后,你就可以声明类库了。让我们看看依赖是如何定义的!

定义依赖

一个依赖是通过group标识符,名字和一个指定版本来确定的。如例:

dependencies {
    compile group:'org.apache.commons',name:'commons-lang3',version:'3.1'
}

在Gradle中,依赖是由configuration分组的。Java插件引入的一种configuration是compile。你可以通过configuration的名字看出它是给编译源代码使用的。

解析依赖

Gradle会自动检测到一个新的依赖添加到项目中。如果依赖没有被成功解析,那么就会在下一个需要使用该依赖的任务启动时去下载它。

 

原文地址:https://www.cnblogs.com/wuchaodzxx/p/7084242.html