Are you looking for an advent calendar? You found it!

Getting Started with Gradle: Our First Java Project

Easy way and hard way sign

This blog post describes how we can compile and package a simple Java project by using Gradle.

Our Java project has only one requirement:

Our build script must create an executable jar file. In other words, we must be able to run our program by using the command:

java -jar jarfile.jar

Let’s find out how we can fulfil this requirement.

Creating a Java Project

We can create a Java project by applying the Java plugin. We can do this by adding the following line to our build.gradle file:

apply plugin: 'java'

That is it. We have now created a Java project.

The Java plugin adds new conventions (e.g. the default project layout), new tasks, and new properties to our build.

Let’s move on and take a quick look at the default project layout.

The Project Layout of a Java Project

The default project layout of a Java project is following:

  • The src/main/java directory contains the source code of our project.
  • The src/main/resources directory contains the resources (such as properties files) of our project.
  • The src/test/java directory contains the test classes.
  • The src/test/resources directory contains the test resources.

All output files of our build are created under the build directory. This directory contains the following subdirectories which are relevant to this blog post (there are other subdirectories too, but we will talk about them in the future):

  • The classes directory contains the compiled .class files.
  • The libs directory contains the jar or war files created by the build.

Let’s move on and add a simple main class to our project.

Adding a Main Class to Our Build

Let’s create a simple main class which prints the words: “Hello World” to System.out. The source code of the HelloWorld class looks as follows:

package net.petrikainulainen.gradle;

public class HelloWorld {

    public static void main(String[] args) {
        System.out.println("Hello World!");
    }
}
The HelloWorld class was added to the src/main/java/net/petrikainulainen/gradle directory.

That is nice. However, we still have to compile and package our project. Let’s move on and take a look at the tasks of a Java project.

The Tasks of a Java Project

The Java plugin adds many tasks to our build but the tasks which are relevant for this blog post are:

  • The assemble task compiles the source code of our application and packages it to a jar file. This task doesn’t run the unit tests.
  • The build task performs a full build of the project.
  • The clean task deletes the build directory.
  • The compileJava task compiles the source code of our application.

We can also get the full list of runnable tasks and their description by running the following command at the command prompt:

gradle tasks

This is a good way to get a brief overview of our project without reading the build script. If we run this command in the root directory of our example project, we see the following output:

> gradle tasks
:tasks

------------------------------------------------------------
All tasks runnable from root project
------------------------------------------------------------

Build tasks
-----------
assemble - Assembles the outputs of this project.
build - Assembles and tests this project.
buildDependents - Assembles and tests this project and all projects that depend on it.
buildNeeded - Assembles and tests this project and all projects it depends on.
classes - Assembles classes 'main'.
clean - Deletes the build directory.
jar - Assembles a jar archive containing the main classes.
testClasses - Assembles classes 'test'.

Build Setup tasks
-----------------
init - Initializes a new Gradle build. [incubating]
wrapper - Generates Gradle wrapper files. [incubating]

Documentation tasks
-------------------
javadoc - Generates Javadoc API documentation for the main source code.

Help tasks
----------
dependencies - Displays all dependencies declared in root project 'first-java-project'.
dependencyInsight - Displays the insight into a specific dependency in root project 'first-java-project'.
help - Displays a help message
projects - Displays the sub-projects of root project 'first-java-project'.
properties - Displays the properties of root project 'first-java-project'.
tasks - Displays the tasks runnable from root project 'first-java-project'.

Verification tasks
------------------
check - Runs all checks.
test - Runs the unit tests.

Rules
-----
Pattern: build<ConfigurationName>: Assembles the artifacts of a configuration.
Pattern: upload<ConfigurationName>: Assembles and uploads the artifacts belonging to a configuration.
Pattern: clean<TaskName>: Cleans the output files of a task.

To see all tasks and more detail, run with --all.

BUILD SUCCESSFUL

Total time: 2.792 secs

Let’s move on and find out how we can package our Java project.

Packaging Our Java Project

We can package our application by using two different tasks:

If the run the command gradle assemble at command prompt, we see the following output:

> gradle assemble
:compileJava
:processResources 
:classes
:jar
:assemble

BUILD SUCCESSFUL

Total time: 3.163 secs

If we run the command gradle build at command prompt, we see the following output:

> gradle build
:compileJava
:processResources 
:classes
:jar
:assemble
:compileTestJava 
:processTestResources 
:testClasses 
:test 
:check 
:build

BUILD SUCCESSFUL

Total time: 3.01 secs

The outputs of these commands demonstrate that the difference of these tasks is that:

  • The assemble task runs only the tasks which are required to package our application.
  • The build task runs the tasks which are required to package our application AND runs automated tests.

Both of these commands create the first-java-project.jar file to the build/libs directory.

The default name of the created jar file is created by using the following template: [project name].jar, and the default name of the project is the same than the name of the directory in which it is created. Because the name of our project directory is first-java-project, the name of created jar is first-java-project.jar.

We can now try to run our application by using the following command:

java -jar first-java-project.jar 

When we do this, we see the following output:

> java -jar first-java.project.jar
No main manifest attribute, in first-java-project.jar

The problem is that we haven’t configured the main class of the jar file in the manifest file. Let’s find out how we can fix this problem.

Configuring the Main Class of a Jar File

The Java plugin adds a jar task to our project, and every jar object has a manifest property which is an instance of Manifest.

We can configure the main class of the created jar file by using the attributes() method of the Manifest interface. In other words, we can specify the attributes added to the manifest file by using a map which contains key-value pairs.

We can set the entry point of our application by setting the value of the Main-Class attribute. After we have made the required changes to the build.gradle file, its source code looks as follows (the relevant part is highlighted):

apply plugin: 'java'

jar {
    manifest {
        attributes 'Main-Class': 'net.petrikainulainen.gradle.HelloWorld'
    }
}
The Java SE tutorial provides more information about the manifest file.

After we have created a new jar file by running either the gradle assemble or gradle build command, we can run the jar file by using the following command:

java -jar first-java-project.jar

When we run our application, the following text is printed to the System.out:

> java -jar first-java-project.jar
Hello World!

That is all for today. Let’s find out what we learned from this blog post.

Summary

We have now created a simple Java project by using Gradle. This blog post has taught us four things:

  • We know that we can create a Java project by applying the Gradle Java plugin.
  • We learned that the default directory layout of a Java project is the same than the default directory layout of a Maven project.
  • We learned that all output files produced by our build can be found from the build directory.
  • We learned how we can customize the attributes added to the manifest file.

P.S. The example project of this blog post is available at Github.

If you enjoyed reading this blog post, you should follow me on Twitter:

About the Author

Petri Kainulainen is passionate about software development and continuous improvement. He is specialized in software development with the Spring Framework and is the author of Spring Data book.

About Petri Kainulainen →

8 comments… add one

  • Hi Petri,

    Nice work. Will you be writing consecutive articles on gradle? Like you do for spring data.

    Reply
    • Hi Akalanka,

      Thank your for your kind words. I really appreciate them.

      And yes, I am going to write a Gradle tutorial which covers the essential parts of Gradle. This tutorial follows the same format as my other tutorials, and the idea is that after this tutorial is over, you should be able to use Gradle in real life software projects.

      Reply
  • Nice Tute Petri . It really helps.

    Reply
    • Thanks! I am happy to hear that blog post was useful to you.

      Reply
  • Hi I have the same use case. I followed the each n every step you said. It didnt work for me. I used the class name & package name, as you did. But didnt work? Any ideas?

    Reply
    • Do you mean that you cannot run the jar file by using a command java -jar jarfile.jar? If so, what kind of an error message did you get?

      Reply
  • Nice basic tutorial on gradle..

    Reply
    • Thank you for your kind words. I really appreciate them.

      Reply

Leave a Comment