Spring Boot 项目构建 之 使用 Gradle 构建 Java 项目(Building Java Projects with Gradle)

Table of contents

Tags

GETTING STARTED

Building Java Projects with Gradle

This guide walks you through using Gradle to build a simple Java project.

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:

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

package hello;

public class HelloWorld {
  public static void main(String[] args) {
    Greeter greeter = new Greeter();
    System.out.println(greeter.sayHello());
  }
}

src/main/java/hello/Greeter.java

package hello;

public class Greeter {
  public String sayHello() {
    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:

:help

Welcome to Gradle 2.3.

To run a build, run gradle <task> ...

To see a list of available tasks, run gradle tasks

To see a list of command-line options, run gradle --help

BUILD SUCCESSFUL

Total 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 SUCCESSFUL

Total 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 run tasksagain 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 tasksagain, 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:

package hello;

import org.joda.time.LocalTime;

public class HelloWorld {
  public static void main(String[] args) {
    LocalTime currentTime = new LocalTime();
    System.out.println("The current local time is: " + currentTime);

    Greeter greeter = new Greeter();
    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.

sourceCompatibility = 1.8
targetCompatibility = 1.8

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.jar
  0 Fri May 30 16:02:32 CDT 2014 META-INF/
 25 Fri May 30 16:02:32 CDT 2014 META-INF/MANIFEST.MF
  0 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 SUCCESSFUL

Total 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’sWAR 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[]
sourceCompatibility = 1.8
targetCompatibility = 1.8

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.

时间: 2024-10-09 11:03:23

Spring Boot 项目构建 之 使用 Gradle 构建 Java 项目(Building Java Projects with Gradle)的相关文章

spring boot 1.5.4 集成Swagger2构建Restful API(十八)

上一篇博客地址:springboot 1.5.4 整合rabbitMQ(十七) 1      Spring Boot集成Swagger2构建RESTful API文档 1.1  Swagger2简介 Swagger2官网:http://swagger.io/ 由于Spring Boot能够快速开发.便捷部署等特性,相信有很大一部分Spring Boot的用户会用来构建RESTful API.而我们构建RESTful API的目的通常都是由于多终端的原因,这些终端会共用很多底层业务逻辑,因此我们会

只需两步!Eclipse+Maven快速构建第一个Spring Boot项目

随着使用Spring进行开发的个人和企业越来越多,Spring从一个单一简洁的框架变成了一个大而全的开源软件,最直观的变化就是Spring需要引入的配置也越来越多.配置繁琐,容易出错,让人无比头疼,简化Spring配置简直可以说是民心所向. Spring Boot是由Pivotal团队提供的一个基于Java的全新的开源框架,其设计目的是用来简化新Spring应用的初始搭建以及开发过程.该框架使用了特定的方式来进行配置,从而使开发人员不再需要定义样板化的配置.如今,Spring Boot逐渐成为快

构建微服务:Spring boot 入门篇

构建微服务:Spring boot 入门篇 什么是spring boot Spring Boot是由Pivotal团队提供的全新框架,其设计目的是用来简化新Spring应用的初始搭建以及开发过程.该框架使用了特定的方式来进行配置,从而使开发人员不再需要定义样板化的配置.用我的话来理解,就是spring boot其实不是什么新的框架,它默认配置了很多框架的使用方式,就像maven整合了所有的jar包,spring boot整合了所有的框架(不知道这样比喻是否合适). 使用spring boot有什

使用Spring Boot构建微服务(文末福利)

本文主要内容 学习微服务的关键特征 了解微服务是如何适应云架构的 将业务领域分解成一组微服务 使用Spring Boot实现简单的微服务 掌握基于微服务架构构建应用程序的视角 学习什么时候不应该使用微服务 软件开发的历史充斥着大型开发项目崩溃的故事,这些项目可能投资了数百万美元.集中了行业里众多的顶尖人才.消耗了开发人员成千上万的工时,但从未给客户交付任何有价值的东西,最终由于其复杂性和负担而轰然倒塌. 这些庞大的项目倾向于遵循大型传统的瀑布开发方法,坚持在项目开始时界定应用的所有需求和设计.这

Spring Boot 2.x基础教程:使用Swagger2构建强大的API文档

随着前后端分离架构和微服务架构的流行,我们使用Spring Boot来构建RESTful API项目的场景越来越多.通常我们的一个RESTful API就有可能要服务于多个不同的开发人员或开发团队:IOS开发.Android开发.Web开发甚至其他的后端服务等.为了减少与其他团队平时开发期间的频繁沟通成本,传统做法就是创建一份RESTful API文档来记录所有接口细节,然而这样的做法有以下几个问题: 由于接口众多,并且细节复杂(需要考虑不同的HTTP请求类型.HTTP头部信息.HTTP请求内容

3.Spring Boot中使用Swagger2构建强大的RESTful API文档

原文:http://www.jianshu.com/p/8033ef83a8ed 由于Spring Boot能够快速开发.便捷部署等特性,相信有很大一部分Spring Boot的用户会用来构建RESTful API.而我们构建RESTful API的目的通常都是由于多终端的原因,这些终端会共用很多底层业务逻辑,因此我们会抽象出这样一层来同时服务于多个移动端或者Web前端. 这样一来,我们的RESTful API就有可能要面对多个开发人员或多个开发团队:IOS开发.Android开发或是Web开发

Spring Boot中使用Swagger2构建强大的RESTful API文档

由于Spring Boot能够快速开发.便捷部署等特性,相信有很大一部分Spring Boot的用户会用来构建RESTful API.而我们构建RESTful API的目的通常都是由于多终端的原因,这些终端会共用很多底层业务逻辑,因此我们会抽象出这样一层来同时服务于多个移动端或者Web前端. 这样一来,我们的RESTful API就有可能要面对多个开发人员或多个开发团队:IOS开发.Android开发或是Web开发等.为了减少与其他团队平时开发期间的频繁沟通成本,传统做法我们会创建一份RESTf

Spring Boot 2.x (十):构建优雅的RESTful接口

RESTful 相信在座的各位对于RESTful都是略有耳闻,那么RESTful到底是什么呢? REST(Representational State Transfer)表述性状态转移是一组架构约束条件和原则.满足这些约束条件和原则的应用程序或设计就是RESTful.需要注意的是,REST是设计风格而不是标准.REST通常基于使用HTTP,URI,和XML(标准通用标记语言下的一个子集)以及HTML(标准通用标记语言下的一个应用)这些现有的广泛流行的协议和标准. 也许这段话有些晦涩难懂,换个角度

java版spring cloud+spring boot 社交电子商务平台(九)使用Swagger2构建强大的RESTful API文档(1)

由于Spring Boot能够快速开发.便捷部署等特性,相信有很大一部分Spring Boot的用户会用来构建RESTful API.而我们构建RESTful API的目的通常都是由于多终端的原因,这些终端会共用很多底层业务逻辑,因此我们会抽象出这样一层来同时服务于多个移动端或者Web前端. 这样一来,我们的RESTful API就有可能要面对多个开发人员或多个开发团队:IOS开发.Android开发或是Web开发等.为了减少与其他团队平时开发期间的频繁沟通成本,传统做法我们会创建一份RESTf