View on GitHub

java-quickstart

Getting started with Java and Gradle

Download this project as a .zip file Download this project as a tar.gz file

Abstract

The purpose of this tutorial is to get you up and running with Java and Gradle as quickly as possible. This tutorial will focus on creating a standard Java library project. Gradle is a robust tool with a huge feature set. Therefore, my goal is to provide you with as much detail as necessary to get started without overwhelming you will a flood of information. I will provide links to the relevant Gradle documentation that you should read when you are ready to dig deeper.

What You Will Learn

  1. How to install gradle
  2. How to generate a project skeleton with gradle
  3. Basic Gradle project structure
  4. Using the Gradle wrapper
  5. Basic Gradle usage

1. Installing Gradle

This tutorial will use Gradle 1.8 which was released 09-24-2013. Please follow the installation instructions provided by the Gradle team to get started.

http://www.gradle.org/docs/1.8/userguide/installation.html

To verify that your installation was successful, open a terminal and run the following command:

gradle --version

If your installation was successful, you should see output that includes the version of Gradle (1.8) along with the versions of Gradle's various dependencies such as Groovy, Ant, Ivy, and Java.

2. Generate a Project Skeleton

Now that you have gradle installed, navigate to the location where you would like to create your project, create a new empty directory called 'java-quickstart', and cd into it.

mkdir java-quickstart
cd java-quickstart

Before we create the project skeleton, let's take a minute to learn a really useful gradle feature. Execute the following command in your terminal:

gradle tasks

You should see a list of the tasks available to you. The list of available tasks will be dependent on your project setup, so it is a good idea to use this command to provide guidance as your project grows. Because we do not have a project created yet, you only see entries related to 'Build Setup' and 'Help'. Notice that there is a 'setupBuild' task available. This is the task that will provide the scaffolding for our project. To create your project execute the following command:

gradle setupBuild --type java-library

This command tells Gradle to create the files neccesary for a Java library project. A Java library project is used to create a jar artifact. If you would like to explore the 'setupBuild' task in more detail check out the documentation here:

http://www.gradle.org/docs/1.8/userguide/build_setup_plugin.html

3. Basic Gradle Project Structure

Take a look at the files that Gradle created for you. You should see a directory structure that looks like this:

java-quickstart/
    build.gradle
    settings.gradle
    src/
    gradle/
    gradlew
    gradlew.bat

The files can be broken down into two categories. They are the standard build files, and files related to the gradle wrapper.

Build Files

The files that are part of the standard Gradle project structure are:

build.gradle

/*
 * This build file was auto generated by running the Gradle 'buildSetup' task
 * by 'chardk' at '10/1/13 10:02 AM' with Gradle 1.8
 *
 * 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 guide available at http://gradle.org/docs/1.8/userguide/tutorial_java_projects.html
 */

// Apply the java plugin to add support for Java
apply plugin: 'java'

// In this section you declare where to find the dependencies of your project
repositories {
    // Use 'maven central' for resolving your dependencies.
    // You can declare any Maven/Ivy/file repository here.
    mavenCentral()
}

// In this section you declare the dependencies for your production and test code
dependencies {
    // The production code uses the SLF4J logging API at compile time
    compile 'org.slf4j:slf4j-api:1.7.5'

    // Declare the dependency for your favourite test framework you want to use in your tests.
    // TestNG is also supported by the Gradle Test task. Just change the
    // testCompile dependency to testCompile 'org.testng:testng:6.8.1' and add
    // 'test.useTestNG()' to your build script.
    testCompile "junit:junit:4.11"
}

This is the project build file. It is where you apply plugins, define repositories, declare dependencies, create tasks, etc. Rather than worry about the details now, just know that the file that was generated for you is all that is neccessary for a simple Java library project. As you become more familiar with Gradle and require additional functionality not offered by this simple build file, take time to read the Gradle documentation. Here are some good places to start:

settings.gradle

/*
 * This settings file was auto generated by the Gradle buildSetup task
 * by 'chardk' at '10/1/13 10:02 AM' with Gradle 1.8
 *
 * The settings file is used to specify which projects to include in your build.
 * In a single project build this file can be empty or even removed.
 *
 * Detailed information about configuring a multi-project build in Gradle can be found
 * in the user guide at http://gradle.org/docs/1.8/userguide/multi_project_builds.html
 */

/*
// To declare projects as part of a multi-project build use the 'include' method
include 'shared'
include 'api'
include 'services:webservice'
*/

rootProject.name = 'java-quickstart'

This file is used to configure various project settings. In the generated file, the only setting that is being applied is assigning a value to rootProject.name. This property will be available in the build.gradle file to be used by the build tasks. As you can see from the comments, another common use of the settings.gradle file is to configure multi-project builds. Multi-project builds are outside the scope of this tutorial, but keep in mind the fact that they are a really nice way to group together related code while maintaining loose coupling. As your project grows, consider refactoring it into several simpler releated projects.

Java Source Files The src directory is where you will create all of your Java source files. The directory layout looks like this:

src/
    main/
        java/
    test/
        java/

You will notice that the 'setupBuild' task created an example source file called 'Library.java' in the main/java directory and an example unit test file called 'LibraryTest.java' in the test/java directory. You should follow these conventions so that Gradle will automatically know where to find your Java files.

4. Using the Gradle Wrapper

Gradle Wrapper Files

The Gradle wrapper provides a way to create a self contained project. This means that you do not have to install Gradle in order to work on a project that contains the wrapper. This is great for a team of developers working on the same project or for working on a project from different computers. Another great use case is for CI servers because no setup needs to be done on the server. All you need to do is grab the project from your SCM and execute gradle commands using the wrapper scripts.

The files that are related to the Gradle wrapper are:

Assume that someone on your team created the project skeleton and checked everything in to source control. For you to start developing on the project, all you need to do is check out the source and start executing commands using the wrapper scripts. There is no need to manually install Gradle on your system. If you are developing on a Unix like system then you will use the gradlew script. Similarly, if you are developing on Windows you will use the gradlew.bat script. The gradle directory contains utilities used by the wrapper and can be ignored for the most part. Let's try running gradle with the wrapper by executing the following command:

gradlew build

The first thing that the script will do is automatically download and configure Gradle for use in your project. The next thing that will happen is Gradle will download the dependencies declared in your build.gradle file. These dependencies will only be downloaded once and then cached on your local drive. Finally, Gradle willl compile your source and test files, execute the tests, and build a jar containing your application code.

You can check out the documentation of the wrapper here:

http://www.gradle.org/docs/1.8/userguide/gradle_wrapper.html

5. Basic Gradle Usage

Gradle embraces the idea of using convention over configuration for you build process. This approach was first taken by Maven in the Java build ecosystem. In practice it turns out that convention will get you most of the way there, but you will most likely require some customization to your build process. Gradle combines the conventions of Maven along with the flexibility of Ant to give you the best of both worlds. In this tutorial, I will not go into the details of the build lifecycle. For a simple project you can get pretty far using just the built in tasks. To get started you only need to know a couple of tasks.

  1. gradlew clean
  2. gradlew test
  3. gradlew build

You may have noticed that after you ran gradlew build, a new directory was created in your project's root directory named 'build'. This directory contains all of the artifacts resulting from building your project.

In order to clean up the files generated by the build process run the following command:

gradlew clean

This should result in the 'build' directory being deleted. At this point your project is back to its initial state.

Next try running this command:

gradlew test

This command instructs Gradle to compile your Java source files, execute your unit tests, and generate the test report. If all of your tests passed you should see a 'BUILD SUCCESSFULL' message.

Finally, run the build command again:

gradlew build

This command will instruct Gradle to compile your Java source files, execute your unit tests, generate a test report, and assemble your jar. You may notice that the some of the steps in the build output are labelled 'UP-TO-DATE'. Gradle is smart enough to keep track of what steps it has already executed and only execute them again if something has changed.

Now try to execute this command:

gradlew clean build

The result of running this command is the same as when you just the gradlew build command. However, notice that most of the build steps in the console's output no longer are marked as 'UP-TO-DATE'. This is because you told Gradle to clean up the build directory before running the build. This means that Gradle had to recompile the sources, rerun the tests, regenerate the test report and finally generate the jar.

A Basic Workflow

To start developing your library, you can follow the simple workflow described below.

  1. Develop a new feature with unit tests
  2. gradlew test
  3. If tests fail, fix the code and go back to step 2
  4. If you need to add more features, go back to step 1
  5. gradlew clean build

At the end of this workflow you should have a unit tested version of 'java-quickstart.jar' that is ready for use.

Using this simple workflow with the default Gradle tasks can actually get you quite a long ways in the development of you project. At some point however, you will most likely need to define your own custom tasks and add additional external dependencies. When you get to that point, check out the following documentation:

The Gradle team has done a really nice job of documenting the tool. All of the references that I have included, plus a ton more are available here:

Gradle 1.8 User Guide

Start Your Project!!!

With what you have learned in this tutorial, you should know everything you need to get started building Java libraries with Gradle.

Contact Me

If you have any questions or would like further clarification, please feel free to shoot me an email. I would be glad to help.

Kevin

krchard@gmail.com