文档章节

Building Java Projects with Gradle

TinkerS
 TinkerS
发布于 2015/03/26 20:22
字数 1954
阅读 948
收藏 6

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 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:

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.

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’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://spring.io/guides/gs/gradle/

共有 人打赏支持
TinkerS
粉丝 8
博文 55
码字总数 12670
作品 0
高级程序员
私信 提问
翻译--Gradle之Java工程入门

我们已经看到Gradle是一个通用构建工具,它可以完成相当多的任务,只要你能在脚本里定义好。如果你没写好脚本,它就啥也干不成。 大部分Java项目都是这样的流程:编译源文件,单元测试,打成...

davelet
2014/01/12
0
0
Kotlin 1.2 M2 发布,1.2 系列的早期访问版

Kotlin 1.2 M2 已发布,此版本的主要是 Kotlin 编译器和工具的稳定性改进和错误修复,以及 Kotlin 标准库的改进。该版本还包括即将发布的 Kotlin 1.1.4 中提供的许多功能。 具体如下: 编译器...

局长
2017/08/10
1K
11
Java程序热加载组件Spring-Loaded

What is Spring Loaded? Spring Loaded is a JVM agent for reloading class file changes whilst a JVM is running. It transforms classes at loadtime to make them amenable to later re......

歇蹩虎子
2014/03/09
0
0
2014终极Java开发者库、工具、人列表

Java developers are flooded with a plethora of libraries and tools for their day-to-day work. We compiled a little list of stuff that we use everyday in primarily business line ......

douxingxiang
2014/12/30
2
0
[雪峰磁针石博客]kotlin书籍汇总

下载地址 Learning Kotlin by Building Android Applications - 2018 初级 Develop amazing applications that will help you understand and explore the fundamentals of Kotlin while co......

python测试开发人工智能安全
2018/08/30
0
0

没有更多内容

加载失败,请刷新页面

加载更多

四、RabbitMQ3.7在CentOS7下的安装

安装依赖 sudo yum install -y gcc gcc-c++ glibc-devel make ncurses-devel openssl-devel autoconf java-1.8.0-openjdk-devel git 创建yum源 vi /etc/yum.repos.d/rabbitmq-erlang.repo [......

XuePeng77
今天
2
0
android 延长Toast的时长

示例:myToast(5000,"hello"); public void myToast(int showTime, String msg) { Toast hello = Toast.makeText(getActivity(), msg, Toast.LENGTH_SHORT); new CountDownTimer(......

雨焰
昨天
4
0
浅谈mybatis的日志适配模式

Java开发中经常用到的日志框架有很多,Log4j、Log4j2、slf4j等等,Mybatis定义了一套统一的日志接口供上层使用,并为上述常用的日志框架提供了相应的适配器。有关适配器模式例子可以参考 设计...

算法之名
昨天
13
0
大数据教程(13.6)sqoop使用教程

上一章节,介绍了sqoop数据迁移工具安装以及简单导入实例的相关知识;本篇博客,博主将继续为小伙伴们分享sqoop的使用。 一、sqoop数据导入 (1)、导入关系表到HIVE ./sqoop import --connect...

em_aaron
昨天
3
0
Git cherry-pick 使用总结

应用背景:假设现在有两个分支:dev_01, dev_02. 如果我想把dev_01分支上的某几个commit合并到dev_02分支, 那么怎么办呢? 这就是cherry-pick的工作了。cherry-pick会捡选某些commit, 即把某...

天王盖地虎626
昨天
9
0

没有更多内容

加载失败,请刷新页面

加载更多

返回顶部
顶部