2019独角兽企业重金招聘Python工程师标准>>> hot3.png

What you’ll build

You’ll create a simple app and then build it using Gradle.

What you’ll need

  • About 15 minutes

  • A favorite text editor or IDE

  • JDK 6 or later

How to complete this guide

Like most Spring Getting Started guides, you can start from scratch and complete each step, or you can bypass basic setup steps that are already familiar to you. Either way, you end up with working code.

To start from scratch, move on to Set up the project.

To skip the basics, do the following:

  • Download and unzip the source repository for this guide, or clone it using Git:git clone https://github.com/spring-guides/gs-gradle.git

  • cd into gs-gradle/initial

  • Jump ahead to Install Gradle.

When you’re finished, you can check your results against the code in gs-gradle/complete.

Set up the project

First you set up a Java project for Gradle to build. To keep the focus on Gradle, make the project as simple as possible for now.

Create the directory structure

In a project directory of your choosing, create the following subdirectory structure; for example, with mkdir -p src/main/java/hello on *nix systems:

└── src└── main└── java└── hello

Within the src/main/java/hello directory, you can create any Java classes you want. For simplicity’s sake and for consistency with the rest of this guide, Spring recommends that you create two classes: HelloWorld.java and Greeter.java.

src/main/java/hello/HelloWorld.java

packagehello;publicclassHelloWorld{publicstaticvoidmain(String[]args){Greetergreeter=newGreeter();System.out.println(greeter.sayHello());}}

src/main/java/hello/Greeter.java

packagehello;publicclassGreeter{publicStringsayHello(){return"Hello world!";}}

Install Gradle

Now that you have a project that you can build with Gradle, you can install Gradle.

Gradle is downloadable as a zip file at http://www.gradle.org/downloads. Only the binaries are required, so look for the link to gradle-version-bin.zip. (You can also choose gradle-version-all.zip to get the sources and documentation as well as the binaries.)

Unzip the file to your computer, and add the bin folder to your path.

To test the Gradle installation, run Gradle from the command-line:

gradle

If all goes well, you see a welcome message:

:helpWelcome to Gradle 2.3.To run a build, run gradle <task> ...To see a list of available tasks, run gradle tasksTo see a list of command-line options, run gradle --helpBUILD SUCCESSFULTotal time: 2.675 secs

You now have Gradle installed.

Find out what Gradle can do

Now that Gradle is installed, see what it can do. Before you even create a build.gradle file for the project, you can ask it what tasks are available:

gradle tasks

You should see a list of available tasks. Assuming you run Gradle in a folder that doesn’t already have a build.gradle file, you’ll see some very elementary tasks such as this:

:tasks== All tasks runnable from root project== Build Setup tasks
setupBuild - Initializes a new Gradle build. [incubating]
wrapper - Generates Gradle wrapper files. [incubating]== Help tasks
dependencies - Displays all dependencies declared in root project 'gs-gradle'.
dependencyInsight - Displays the insight into a specific dependency in root project 'gs-gradle'.
help - Displays a help message
projects - Displays the sub-projects of root project 'gs-gradle'.
properties - Displays the properties of root project 'gs-gradle'.
tasks - Displays the tasks runnable from root project 'gs-gradle'.To see all tasks and more detail, run with --all.BUILD SUCCESSFULTotal time: 3.077 secs

Even though these tasks are available, they don’t offer much value without a project build configuration. As you flesh out the build.gradle file, some tasks will be more useful. The list of tasks will grow as you add plugins to build.gradle, so you’ll occasionally want to runtasks again to see what tasks are available.

Speaking of adding plugins, next you add a plugin that enables basic Java build functionality.

Build Java code

Starting simple, create a very basic build.gradle file that has only one line in it:

apply plugin:'java'

This single line in the build configuration brings a significant amount of power. Run gradle tasks again, and you see new tasks added to the list, including tasks for building the project, creating JavaDoc, and running tests.

You’ll use the gradle build task frequently. This task compiles, tests, and assembles the code into a JAR file. You can run it like this:

gradle build

After a few seconds, "BUILD SUCCESSFUL" indicates that the build has completed.

To see the results of the build effort, take a look in the build folder. Therein you’ll find several directories, including these three notable folders:

  • classes. The project’s compiled .class files.

  • reports. Reports produced by the build (such as test reports).

  • libs. Assembled project libraries (usually JAR and/or WAR files).

The classes folder has .class files that are generated from compiling the Java code. Specifically, you should find HelloWorld.class and Greeter.class.

At this point, the project doesn’t have any library dependencies, so there’s nothing in thedependency_cache folder.

The reports folder should contain a report of running unit tests on the project. Because the project doesn’t yet have any unit tests, that report will be uninteresting.

The libs folder should contain a JAR file that is named after the project’s folder. Further down, you’ll see how you can specify the name of the JAR and its version.

Declare dependencies

The simple Hello World sample is completely self-contained and does not depend on any additional libraries. Most applications, however, depend on external libraries to handle common and/or complex functionality.

For example, suppose that in addition to saying "Hello World!", you want the application to print the current date and time. You could use the date and time facilities in the native Java libraries, but you can make things more interesting by using the Joda Time libraries.

First, change HelloWorld.java to look like this:

packagehello;importorg.joda.time.LocalTime;publicclassHelloWorld{publicstaticvoidmain(String[]args){LocalTimecurrentTime=newLocalTime();System.out.println("The current local time is: "+currentTime);Greetergreeter=newGreeter();System.out.println(greeter.sayHello());}}

Here HelloWorld uses Joda Time’s LocalTime class to get and print the current time.

If you ran gradle build to build the project now, the build would fail because you have not declared Joda Time as a compile dependency in the build.

For starters, you need to add a source for 3rd party libraries.

repositories{mavenCentral()}

The repositories block indicates that the build should resolve its dependencies from the Maven Central repository. Gradle leans heavily on many conventions and facilities established by the Maven build tool, including the option of using Maven Central as a source of library dependencies.

Now that we’re ready for 3rd party libraries, let’s declare some.

dependencies{compile"joda-time:joda-time:2.2"}

With the dependencies block, you declare a single dependency for Joda Time. Specifically, you’re asking for (reading right to left) version 2.2 of the joda-time library, in the joda-time group.

Another thing to note about this dependency is that it is a compile dependency, indicating that it should be available during compile-time (and if you were building a WAR file, included in the /WEB-INF/libs folder of the WAR). Other notable types of dependencies include:

  • providedCompile. Required dependencies for compiling the project code, but that will be provided at runtime by a container running the code (for example, the Java Servlet API).

  • testCompile. Dependencies used for compiling and running tests, but not required for building or running the project’s runtime code.

Finally, let’s specify the name for our JAR artifact.

jar{baseName='gs-gradle'version='0.1.0'}

The jar block specifies how the JAR file will be named. In this case, it will rendergs-gradle-0.1.0.jar.

Now if you run gradle build, Gradle should resolve the Joda Time dependency from the Maven Central repository and the build will succeed.

Build your project with Gradle Wrapper

The Gradle Wrapper is the preferred way of starting a Gradle build. It consists of a batch script for Windows and a shell script for OS X and Linux. These scripts allow you to run a Gradle build without requiring that Gradle be installed on your system. To make this possible, add the following block to the bottom of your build.gradle.

task wrapper(type:Wrapper){gradleVersion='2.3'}

Run the following command to download and initialize the wrapper scripts:

gradle wrapper

After this task completes, you will notice a few new files. The two scripts are in the root of the folder, while the wrapper jar and properties files have been added to a new gradle/wrapperfolder.

└── initial└── gradlew└── gradlew.bat└── gradle└── wrapper└── gradle-wrapper.jar└── gradle-wrapper.properties

The Gradle Wrapper is now available for building your project. Add it to your version control system, and everyone that clones your project can build it just the same. It can be used in the exact same way as an installed version of Gradle. Run the wrapper script to perform the build task, just like you did previously:

./gradlew build

The first time you run the wrapper for a specified version of Gradle, it downloads and caches the Gradle binaries for that version. The Gradle Wrapper files are designed to be committed to source control so that anyone can build the project without having to first install and configure a specific version of Gradle.

At this stage, you will have built your code. You can see the results here:

build
├── classes
│   └── main
│       └── hello
│           ├── Greeter.class
│           └── HelloWorld.class
├── dependency-cache
├── libs
│   └── gs-gradle-0.1.0.jar
└── tmp└── jar└── MANIFEST.MF

Included are the two expected class files for Greeter and HelloWorld, as well as a JAR file. Take a quick peek:

$ jar tvf build/libs/gs-gradle-0.1.0.jar0 Fri May 30 16:02:32 CDT 2014 META-INF/25 Fri May 30 16:02:32 CDT 2014 META-INF/MANIFEST.MF0 Fri May 30 16:02:32 CDT 2014 hello/
369 Fri May 30 16:02:32 CDT 2014 hello/Greeter.class
988 Fri May 30 16:02:32 CDT 2014 hello/HelloWorld.class

The class files are bundled up. It’s important to note, that even though you declared joda-time as a dependency, the library isn’t included here. And the JAR file isn’t runnable either.

To make this code runnable, we can use gradle’s application plugin. Add this to yourbuild.gradle file.

apply plugin: 'application'mainClassName = 'hello.HelloWorld'

Then you can run the app!

$ ./gradlew run
:compileJava UP-TO-DATE
:processResources UP-TO-DATE
:classes UP-TO-DATE
:run
The current local time is: 16:16:20.544
Hello world!BUILD SUCCESSFULTotal time: 3.798 secs

To bundle up dependencies requires more thought. For example, if we were building a WAR file, a format commonly associated with packing in 3rd party dependencies, we could use gradle’s WAR plugin. If you are using Spring Boot and want a runnable JAR file, the spring-boot-gradle-plugin is quite handy. At this stage, gradle doesn’t know enough about your system to make a choice. But for now, this should be enough to get started using gradle.

To wrap things up for this guide, here is the completed build.gradle file:

build.gradle

apply plugin:'java'apply plugin:'eclipse'apply plugin:'application'mainClassName='hello.HelloWorld'// tag::repositories[]repositories{mavenCentral()}// end::repositories[]// tag::jar[]jar{baseName='gs-gradle'version='0.1.0'}// end::jar[]// tag::dependencies[]dependencies{compile"joda-time:joda-time:2.2"}// end::dependencies[]// tag::wrapper[]task wrapper(type:Wrapper){gradleVersion='2.3'}// end::wrapper[]

 There are many start/end comments embedded here. This makes it possible to extract bits of the build file into this guide for the detailed explanations above. You don’t need them in your production build file.

Summary

Congratulations! You have now created a simple yet effective Gradle build file for building Java projects.

转载于:https://my.oschina.net/redhouse/blog/392263

Building Java Projects with Gradle相关推荐

  1. java tekv_java 10 gradle项目:找不到自动模块

    我使用gradle创建了一个带有intelliJ的java 10项目 . 我复制了一些东西(一些使用库guava和javaFx的"AppFx"类,以及一个个人的build.grad ...

  2. Java Maven和Gradle构建的主题缓存

    Concourse CI 3.3.x引入了在任务运行之间缓存路径的功能. 此功能有助于加快将内容缓存在特定文件夹中的任务-在这里,我将演示如何使用此功能来加快基于Maven和Gradle的Java构建 ...

  3. Java EE,Gradle和集成测试

    在过去的几年中,Apache Maven已成为Java和Java EE项目的事实上的构建工具. 但是从两年前开始, Gradle便获得了越来越多的用户. 在我之前的文章( http://www.lor ...

  4. gradle java ide_使用Gradle构建Java项目

    使用Gradle构建Java项目 这个手册将通过一个简单的Java项目向大家介绍如何使用Gradle构建Java项目. 我们将要做什么? 我们将在这篇文档航中创建一个简单的Java项目,然后使用Gra ...

  5. java中什么是task_关于java:深入理解gradle中的task

    简介 在之前的文章中,咱们讲到了如何应用gradle创立一个简略的task,以及task之间怎么依赖,甚至应用了程序来创立task.在本文中,咱们会更加深刻的去理解一下gradle中的task. 定义 ...

  6. 【译】Spring 官方教程:使用 Restdocs 创建 API 文档

    原文:Creating API Documentation with Restdocs 译者:HoldDie 校对:Jitianyu 本指南将引导你了解在 Spring 应用程序中为 HTTP 端点( ...

  7. 用小说的形式讲解Spring(4) —— 使用Spring Boot创建NoXml的Web应用

    本文发布于专栏Effective Java,如果您觉得看完之后对你有所帮助,欢迎订阅本专栏,也欢迎您将本专栏分享给您身边的工程师同学. 本文中的项目使用Github托管,已打Tag,执行git che ...

  8. 计算机类免费电子书共享

    列表最早来自stackoverflow上的一个问题:List of freely available programming books 现在在github上进行维护:free-programming ...

  9. Gradle2.0用户指南翻译——第七章. Java 快速入门

    翻译项目请关注Github上的地址: https://github.com/msdx/gradledoc 本文翻译所在分支: https://github.com/msdx/gradledoc/tre ...

最新文章

  1. office使用技巧
  2. Linux下查看文件或文件夹大小的命令df 、du、ls
  3. uvalive3209City Game
  4. 信息学奥赛一本通(1402:Vigenère密码)
  5. C#算法设计排序篇之07-希尔排序(附带动画演示程序)
  6. VS2008中 没有QT的代码智能提示
  7. Python学习之路-22 (面向对象特殊成员)
  8. 如何为 Mac 添加新语言?
  9. R语言实现K最近邻算法(KNN)
  10. Netty4.0学习笔记系列之五:自定义通讯协议
  11. 华云数据入围2021新经济年度巅峰榜
  12. 新词发现-helloNLP
  13. 001_linux基础命令
  14. 皮卡丘(pikachu)RCE
  15. 微信小程序webview清除缓存、微信公众号h5清除缓存、页面白屏、空白、不刷新问题
  16. Linux下线程池概念详解以及代码演示
  17. TensorFlow进行多元线性回归
  18. 基于RNN实现垃圾邮件辨别
  19. 任天堂switch修改服务器,任天堂switch将退在线服务器 玩家似乎并不买账
  20. 九坤德州扑克第一名方案分享

热门文章

  1. oracle按空格拆分列,DB2字符串按照指定符号进行拆分成多个字段的实现方式
  2. VMTK学习——02.基本的PYPES教程
  3. 「镁客·请讲」深睿医疗乔昕:AI医疗才起步,说变革尚早
  4. Visual Studio 2017 15.8概览
  5. 除了密钥,公有云还有哪些安全保护方式
  6. NOIP2013pj车站分级[拓扑排序]
  7. java 调用mysql存储过程
  8. Json串到json对象的转换
  9. 使用jQuery的9个误区
  10. 海量数据处理的思路和方法