Gradle 创建java项目详细步骤

Java构建工具三强: Ant, Maven, Gradle

Ant历史悠久, 用build.xml 描述, 当时他的xml着实让很多工程师头痛, 但仍有用武之地. 

Maven 用pom.xml 文件描述, 是对ant的补充, 项目统一管理的得力助手, 统一的依赖包使得项目不再为版本不一致而发愁.

Gradle 用build.gradle文件, 可读性更强, 使用更方便, 可谓如日中天.

来自百科解读:

Gradle是一个基于Apache Ant和Apache Maven概念项目自动化构建开源工具。它使用基于Groovy的特定领域语言(DSL)来声明项目设置,抛弃了基于XML的各种繁琐配置。

面向Java应用为主, 当前支持的语言限于Java、Groovy、Kotlin和Scala,计划未来将支持更多的语言。

功能

  • gradle对多工程的构建支持很出色,工程依赖是gradle的第一公民。

  • gradle支持局部构建。

  • 支持多方式依赖管理:包括从maven远程仓库、nexus私服、ivy仓库以及本地文件系统的jars或者dirs

  • gradle是第一个构建集成工具,与ant、maven、ivy有良好的相容相关性。

  • 轻松迁移:gradle适用于任何结构的工程,你可以在同一个开发平台平行构建原工程和gradle工程。通常要求写相关测试,以保证开发的插件的相似性,这种迁移可以减少破坏性,尽可能的可靠。这也是重构的最佳实践。

  • gradle的整体设计是以作为一种语言为导向的,而非成为一个严格死板的框架。

  • 免费开源

安装之前需要什么?

  • 需要java 1.7 以上版本

  • 选择gradle 4.3 以上版本

本文推荐java 1.8 +Gradle 5.4

Windows用户下载安装包:https://gradle.org/next-steps/?version=5.4.1&format=bin

Mac os 或者 Linux 用户更为简单

$ brew install gradle

Updating Homebrew...

==> Auto-updated Homebrew!

Updated 2 taps (homebrew/cask and homebrew/core).

==> Updated Formulae

sphinx-doc ✔                     grakn                            jenkins-lts                      tomcat

==> Downloading https://services.gradle.org/distributions/gradle-5.4.1-all.zip

==> Downloading from https://downloads.gradle.org/distributions/gradle-5.4.1-all.zip

######################################################################## 100.0%

 /usr/local/Cellar/gradle/5.4.1: 13,767 files, 235.5MB, built in 2 minutes 13 seconds

$ gradle -v

Welcome to Gradle 5.4.1!

Here are the highlights of this release:

 - Run builds with JDK12

 - New API for Incremental Tasks

 - Updates to native projects, including Swift 5 support

For more details see https://docs.gradle.org/5.4.1/release-notes.html

------------------------------------------------------------

Gradle 5.4.1

------------------------------------------------------------

Build time:   2019-04-26 08:14:42 UTC

Revision:     261d171646b36a6a28d5a19a69676cd098a4c19d

Kotlin:       1.3.21

Groovy:       2.5.4

Ant:          Apache Ant(TM) version 1.9.13 compiled on July 10 2018

JVM:          1.8.0_161 (Oracle Corporation 25.161-b12)

OS:           Mac OS X 10.13.6 x86_64

安装信息告诉我们gradle安装路径是: /usr/local/Cellar/gradle/5.4.1

设置环境变量: (推荐)

以mac 为例

$ vi ~/.bash_profile 增加如下内容

$ export PATH=$PATH:/opt/gradle/gradle-5.4.1/bin

$ source ~/.bash_profile     //立刻生效

Windows 用户:

path中增加  C:\Gradle\gradle-5.4.1\bin 具体根据你安装的目录配置

验证安装初始化:

louiezhou$ gradle -v

------------------------------------------------------------

Gradle 5.4.1

------------------------------------------------------------

Build time:   2019-04-26 08:14:42 UTC

Revision:     261d171646b36a6a28d5a19a69676cd098a4c19d

Kotlin:       1.3.21

Groovy:       2.5.4

Ant:          Apache Ant(TM) version 1.9.13 compiled on July 10 2018

JVM:          1.8.0_161 (Oracle Corporation 25.161-b12)

OS:           Mac OS X 10.13.6 x86_64

查看使用方法:

louiezhou$ gradle -h

USAGE: gradle [option...] [task...]

-?, -h, --help            Shows this help message.

-a, --no-rebuild          Do not rebuild project dependencies.

-b, --build-file          Specify the build file.

--build-cache             Enables the Gradle build cache. Gradle will try to reuse outputs from previous builds.

-c, --settings-file       Specify the settings file.

--configure-on-demand     Configure necessary projects only. Gradle will attempt to reduce configuration time for large multi-project builds. [incubating]

--console                 Specifies which type of console output to generate. Values are 'plain', 'auto' (default), 'rich' or 'verbose'.

--continue                Continue task execution after a task failure.

-D, --system-prop         Set system property of the JVM (e.g. -Dmyprop=myvalue).

-d, --debug               Log in debug mode (includes normal stacktrace).

--daemon                  Uses the Gradle Daemon to run the build. Starts the Daemon if not running.

--foreground              Starts the Gradle Daemon in the foreground.

-g, --gradle-user-home    Specifies the gradle user home directory.

-I, --init-script         Specify an initialization script.

-i, --info                Set log level to info.

--include-build           Include the specified build in the composite.

-m, --dry-run             Run the builds with all task actions disabled.

--max-workers             Configure the number of concurrent workers Gradle is allowed to use.

--no-build-cache          Disables the Gradle build cache.

--no-configure-on-demand  Disables the use of configuration on demand. [incubating]

--no-daemon               Do not use the Gradle daemon to run the build. Useful occasionally if you have configured Gradle to always run with the daemon by default.

--no-parallel             Disables parallel execution to build projects.

--no-scan                 Disables the creation of a build scan. For more information about build scans, please visit https://gradle.com/build-scans.

--offline                 Execute the build without accessing network resources.

-P, --project-prop        Set project property for the build script (e.g. -Pmyprop=myvalue).

-p, --project-dir         Specifies the start directory for Gradle. Defaults to current directory.

--parallel                Build projects in parallel. Gradle will attempt to determine the optimal number of executor threads to use.

--priority                Specifies the scheduling priority for the Gradle daemon and all processes launched by it. Values are 'normal' (default) or 'low' [incubating]

--profile                 Profile build execution time and generates a report in the <build_dir>/reports/profile directory.

--project-cache-dir       Specify the project-specific cache directory. Defaults to .gradle in the root project directory.

-q, --quiet               Log errors only.

--refresh-dependencies    Refresh the state of dependencies.

--rerun-tasks             Ignore previously cached task results.

-S, --full-stacktrace     Print out the full (very verbose) stacktrace for all exceptions.

-s, --stacktrace          Print out the stacktrace for all exceptions.

--scan                    Creates a build scan. Gradle will emit a warning if the build scan plugin has not been applied. (https://gradle.com/build-scans)

--status                  Shows status of running and recently stopped Gradle Daemon(s).

--stop                    Stops the Gradle Daemon if it is running.

-t, --continuous          Enables continuous build. Gradle does not exit and will re-execute tasks when task file inputs change.

  1 export PATH=/opt/local/bin:/opt/local/sbin:$PATH

--update-locks            Perform a partial update of the dependency lock, letting passed in module notations change version. [incubating]

-v, --version             Print version info.

-w, --warn                Set log level to warn.

--warning-mode            Specifies which mode of warnings to generate. Values are 'all', 'summary'(default) or 'none'

--write-locks             Persists dependency resolution for locked configurations, ignoring existing locking information if it exists [incubating]

-x, --exclude-task        Specify a task to be excluded from execution.

一. 创建java application:

louiezhou$ mkdir demo   #创建一个目录

louiezhou$ cd demo/

louiezhou$ gradle init       #初始化创建项目

Select type of project to generate:

  1: basic

  2: cpp-application

  3: cpp-library

  4: groovy-application

  5: groovy-library

  6: java-application

  7: java-library

  8: kotlin-application

  9: kotlin-library

  10: scala-library

Enter selection (default: basic) [1..10] 6

Select build script DSL:

  1: groovy

  2: kotlin

Enter selection (default: groovy) [1..2] 1

Select test framework:

  1: junit

  2: testng

  3: spock

Enter selection (default: junit) [1..3] 2     //我选择了testng为测试框架

Project name (default: demo):

Source package (default: demo):

BUILD SUCCESSFUL in 22s

2 actionable tasks: 2 executed

初始化自动生成目录:

build.gradle    gradle          gradlew         gradlew.bat     settings.gradle src

初始化结束后, 选择一个个人喜好的编辑器, 个人比较这喜欢Atom or Sublime 轻巧方便, 不像Eclipse或者intelliJ那样庞大笨重.

打开Atom 导入工程即可浏览目录.

├── build.gradle

├── gradle            #wrapper的文件

│   └── wrapper

│       ├── gradle-wrapper.jar

│       └── gradle-wrapper.properties

├── gradlew

├── gradlew.bat

├── settings.gradle

└── src

    ├── main

    │   └── java        #源代码

    │       └── App.java

    └── test            #测试代码

        └── java

            └── AppTest.java

--------------------- 

App.java

/*

 * This Java source file was generated by the Gradle 'init' task.

 */

package demo;

public class App {

    public String getGreeting() {

        return "Hello world, this is a first gradle application + 中文测试!";

    }

    public static void main(String[] args) {

        System.out.println(new App().getGreeting());

    }

}

AppTest.java

/*

 * This Java source file was generated by the Gradle 'init' task.

 */

package demo;

import org.testng.annotations.*;

import static org.testng.Assert.*;

public class AppTest {

    @Test public void appHasAGreeting() {

        App classUnderTest = new App();

        assertNotNull(classUnderTest.getGreeting(), "app should have a greeting");

    }

}

settings.gradle

rootProject.name = 'demo'

配置build.gradle

/*

 * This file was generated by the Gradle 'init' task.

 *

 * 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 Manual available at https://docs.gradle.org/5.4.1/userguide/tutorial_java_projects.html

 */

plugins {

    // Apply the java plugin to add support for Java

    id 'java'    #java插件

    // Apply the application plugin to add support for building an application

    id 'application' 

}

repositories {

    // Use jcenter for resolving your dependencies.

    // You can declare any Maven/Ivy/file repository here.

    jcenter()     #公有仓库

}

/****编译编码,解决Gradle编译时出现:编码GBK的不可映射字符****/

[compileJava, compileTestJava]*.options*.encoding = 'UTF-8'

dependencies {     #添加依赖

    // This dependency is found on compile classpath of this component and consumers.

    implementation 'com.google.guava:guava:27.0.1-jre'   #依赖google的guava

    // Use TestNG framework, also requires calling test.useTestNG() below

    testImplementation 'org.testng:testng:6.14.3'  #依赖testNG测试库

}

// Define the main class for the application

mainClassName = 'demo.App'   #main 类

test {

    // Use TestNG for unit tests

    useTestNG()   #testNT 单元测试

}

二. 执行构建

louie-mac:demo louiezhou$ ./gradlew build

BUILD SUCCESSFUL in 25s

7 actionable tasks: 7 executed

louie-mac:demo louiezhou$ ls

build           build.gradle    gradle          gradlew         gradlew.bat     settings.gradle src

当我们执行完build命令后, 会在项目目录中生成class文件  目录:build->classes->java->main->demo->App.class

三. 因为Gradle构建使用了Application plugin,使用tasks任务来查看插件添加的那些任务

louie-mac:demo louiezhou$ ./gradlew tasks

> Task :tasks

------------------------------------------------------------

Tasks runnable from root project

------------------------------------------------------------

Application tasks

-----------------

run - Runs this project as a JVM application

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.

wrapper - Generates Gradle wrapper files.

Distribution tasks

------------------

assembleDist - Assembles the main distributions

distTar - Bundles the project as a distribution.

distZip - Bundles the project as a distribution.

installDist - Installs the project as a distribution as-is.

Documentation tasks

-------------------

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

Help tasks

----------

buildEnvironment - Displays all buildscript dependencies declared in root project 'demo'.

components - Displays the components produced by root project 'demo'. [incubating]

dependencies - Displays all dependencies declared in root project 'demo'.

dependencyInsight - Displays the insight into a specific dependency in root project 'demo'.

dependentComponents - Displays the dependent components of components in root project 'demo'. [incubating]

help - Displays a help message.

model - Displays the configuration model of root project 'demo'. [incubating]

projects - Displays the sub-projects of root project 'demo'.

properties - Displays the properties of root project 'demo'.

tasks - Displays the tasks runnable from root project 'demo'.

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 gradlew tasks --all

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

BUILD SUCCESSFUL in 2s

1 actionable task: 1 executed

四. 最后就是run

louie-mac:demo louiezhou$ ./gradlew run

> Task :run

Hello world, this is a first gradle application + 中文测试! #App 的main 输出我们设定的内容

BUILD SUCCESSFUL in 1s

2 actionable tasks: 1 executed, 1 up-to-date

参考文献: https://gradle.org/install/

尚书·大禹谟---人心惟危,道心惟微,惟精惟一,允执厥中, 天之历数在尔躬,允执其中. 

中考加油!!

今日推荐阅读文章精选推荐

为什么要做接口测试

JMeter数据库操作

Jmeter接口测试-正则表达式

JMeter中文返回乱码

Jmeter接口测试-参数化

JMeter接口测试-基础

测试-感想

微信长按二维码添加作者

      获取更多精彩内容

赶紧关注我们吧

欢迎自荐和推荐, 需要的微信推送简历!

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值