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:
-
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
package hello;publicclassHelloWorld{publicstaticvoid main(String[] args){Greeter greeter =newGreeter();System.out.println(greeter.sayHello());}}
src/main/java/hello/Greeter.java
package hello;publicclassGreeter{publicString 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 1.8. 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 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'
apply plugin:'eclipse'// 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 ='1.11'}// end::wrapper[]
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:
package hello;import org.joda.time.LocalTime;publicclassHelloWorld{publicstaticvoid main(String[] args){LocalTime currentTime =newLocalTime();System.out.println("The current local time is: "+ currentTime);Greeter greeter =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 ='1.11'}
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/wrapper
folder.
└── 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.
Here is the completed build.gradle
file:
build.gradle
apply plugin:'java'
apply plugin:'eclipse'// 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 ='1.11'}// end::wrapper[]
Summary
Congratulations! You have now created a simple yet effective Gradle build file for building Java projects.
相关推荐
Build and test software written in Java and many other languages with Gradle, the open source project automation tool that's getting a lot of attention. This concise introduction provides numerous ...
本书《Building and Testing with Gradle》由Tim Berglund和Matthew McCullough撰写,深入探讨了如何使用Gradle进行高效的构建与测试。书中不仅涵盖了Gradle的基本用法,还介绍了如何利用Gradle的高级特性来优化构建...
本篇文章将深入探讨如何使用Gradle这一现代、灵活的构建工具来构建简单的Java程序。Gradle以其强大的插件生态系统和基于Groovy的DSL(领域特定语言)而闻名,使得构建过程变得更为简洁易懂。 首先,让我们理解什么...
Master the fundamentals of Gradle using real-world projects with this quick and easy-to-read guide About This Book Write beautiful build scripts for various types of projects effortlessly Become more...
【Java 11和Gradle简介】 Java 11是Oracle公司发布的长期支持(LTS)版本,作为Java平台标准版(Java SE)的一部分。它在2018年9月25日正式发布,带来了许多新特性、改进和优化。其中,最重要的特性包括HTTP客户端...
You will also get hands-on with building and testing projects using Gradle. You will then begin to cover diverse topics, such as Continuous Integration with Jenkins and TeamCity, Migration strategies...
在提供的部分内容中,提到了《Building and Testing with Gradle》一书,这本书由Tim Berglund和Matthew McCullough所著,是关于使用Gradle进行项目构建和测试的详细指南。书中不仅包含了前言,还有由Gradleware的...
`javacard-gradle-plugin`是一个专门为JavaCard开发设计的Gradle插件,目的是简化JavaCard项目的构建流程,提高开发效率。Gradle是一种强大的构建自动化工具,广泛应用于Java项目,它的灵活性和可扩展性使其成为Java...
java gradle开发模式下的雷霆战机小游戏java gradle开发模式下的雷霆战机小游戏 java gradle开发模式下的雷霆战机小游戏java gradle开发模式下的雷霆战机小游戏 java gradle开发模式下的雷霆战机小游戏java gradle...
java maven gradle 3.0.1, 国内不好下载的资源,开发android 必备哦。
Java 和 Gradle 是现代Java开发中的重要组成部分。Java是一种广泛使用的面向对象的编程语言,而Gradle则是一种强大的构建自动化工具。本项目“java-sample_java_Gradle_”显然是一个包含Java代码示例并使用Gradle...
SpringBoot、Gradle、Maven、Java和Groovy是Java生态系统中的重要组成部分,它们在现代软件开发中扮演着至关重要的角色。这篇详细的知识点解析将深入探讨这些技术及其相互关系。 1. **SpringBoot**: SpringBoot是...
gradle-android-javadoc-plugin Gradle插件,可从Android Gradle项目生成Java文档。 与最新的Gradle Android Tools版本3.0.1一起使用。 设置app / build.gradle或library / build.gra gradle-android-javadoc-plugin...
为了顺利进行Spring项目的开发,首先需要构建一个稳定的基础环境,而这个环境的核心就是Java开发工具包(JDK)和构建工具(Gradle)。本篇文章将详细讲解如何使用Jdk1.8.0_231和Gradle4.9来搭建适用于Spring 5.0.x的...