Gradle is an open source build automation system that replaces XML based build scripts with an internal DSL that is based on Groovy programming language. In this journal entry, we will be journeying on “How to Build Java Project using Gradle”.
Simple Java Project using Gradle
#1: Setup the Java Project
The very first step is to create the project folder where we will be working on creating this project. For simplicity sake let’s keep a very simple name of the folder “getting-started-gradle”.
$ mkdir getting-started-gradle
Once the project folder is created, let’s move into that folder and create the java project structure inside that.
// *nix System $ mkdir -p src/main/java/hello
Within this directory, we can create our java classes and we can make as many classes as we want. But for this example, we will be creating only two classes namely "HelloWorld.java"
and "GreetMessage.java"
src/main/java/hello/HelloWorld.java
package hello; public class HelloWorld { public static void main(String[] args) { GreetMessage greetMessage = new GreetMessage(); System.out.println(greetMessage.displayMessage()); } }
src/main/java/hello/GreetMessage.java
package hello; public class GreetMessage { public String displayMessage() { return "Hello world!"; } }
#2: Install Gradle
Now that you have a project that you can build with Gradle, you can install Gradle.
It’s highly recommended to use an installer:
As a last resort, if neither of these tools suit your needs, you can download the binaries from 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 will see the output as:
:help Welcome to Gradle 1.10. 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: 5.446 secs
The above output confirms that the Gradle has been installed on your machine. Now let’s find out what Gradle can do for us before we even create the famous build.gradle
file.
Run the following command on the terminal to see the list of gradle tasks that are available.
$ gradle tasks
The output of the above command should look like this:
:tasks ------------------------------------------------------------ All tasks runnable from root project ------------------------------------------------------------ Build Setup tasks ----------------- init - Initializes a new Gradle build. [incubating] wrapper - Generates Gradle wrapper files. [incubating] Help tasks ---------- dependencies - Displays all dependencies declared in root project 'java'. dependencyInsight - Displays the insight into a specific dependency in root project 'java'. help - Displays a help message projects - Displays the sub-projects of root project 'java'. properties - Displays the properties of root project 'java'. tasks - Displays the tasks runnable from root project 'java'. To see all tasks and more detail, run with --all. BUILD SUCCESSFUL Total time: 4.119 secs
The list of tasks will grow as you add plugins to build.gradle
, so you’ll occasionally want to run tasks again to see what tasks are available.
Speaking of adding plugins, next you add a plugin that enables basic Java build functionality.
#3: Build Java code
Starting simple, create a very basic build.gradle
file in the <project folder> you created at the beginning of this guide. Give it just one line:
apply plugin: 'java'
The above specified single line in the build configuration brings a significant amount of power. Run the gradle task command 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 the dependency_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.
#4: 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); GreetMessage greetMessage = new GreetMessage(); System.out.println(greetMessage.displayMessage()); } }
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" testCompile "junit:junit:4.12" }
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.
To wrap things up for this guide, here is the completed build.gradle
file:
build.gradle
apply plugin: 'java' repositories { mavenCentral() } sourceCompatibility = 1.8 targetCompatibility = 1.8 dependencies { compile "joda-time:joda-time:2.2" testCompile "junit:junit:4.12" }
In the next journal entry, we will be looking at the use of Gradle Wrapper to build and run our java application. So stay tuned and connected by subscribing to our newsletter or you can join us on our social platforms – facebook, twitter, google+.