1. Overview
This tutorial provides a practical guide on how to build a Java-based project using Gradle.
We'll explain the steps of manually creating a project structure, performing the initial configuration, and adding the Java plug-in and JUnit dependency. Then, we'll build and run the application.
Finally, in the last section, we'll give an example of how to do this with the Gradle Build Init Plugin. Some basic introduction can be also found in the article Introduction to Gradle.
2. Java Project Structure
Before we manually create a Java project and prepare it for build, we need to install Gradle.
Let's start creating a project folder using the PowerShell console with name gradle-employee-app:
> mkdir gradle-employee-app
After that, let's navigate to the project folder and create sub-folders:
> mkdir src/main/java/employee
The resulting output is shown:
Directory: D:\gradle-employee-app\src\main\java Mode LastWriteTime Length Name ---- ------------- ------ ---- d----- 4/10/2020 12:14 PM employee
Within the project structure above, let's create two classes. One is a simple Employee class with data such as name, email address, and year of birth:
public class Employee { String name; String emailAddress; int yearOfBirth; }
The second is the main Employee App class that prints Employee data:
public class EmployeeApp { public static void main(String[] args){ Employee employee = new Employee(); employee.name = "John"; employee.emailAddress = "john@baeldung.com"; employee.yearOfBirth = 1978; System.out.println("Name: " + employee.name); System.out.println("Email Address: " + employee.emailAddress); System.out.println("Year Of Birth:" + employee.yearOfBirth); } }
3. Build a Java Project
Next, to build our Java project, we create a build.gradle configuration file in project root folder.
The following is in the PowerShell command-line:
Echo > build.gradle
We skip the next step related to the input parameters:
cmdlet Write-Output at command pipeline position 1 Supply values for the following parameters: InputObject[0]:
For a build to be successful, we need to add a Java Library and Application Plugin:
plugins { id 'java-library' id 'application' }
To use these plug-ins we apply an application plugin and add a fully-qualified name of the main class:
apply plugin: 'application' mainClassName = 'employee.EmployeeApp'
Each project consists of tasks. A task represents a piece of work that a build performs such as compiling the source code.
For instance, we can add a task to the configuration file that prints a message about the completed project configuration:
println 'This is executed during configuration phase' task configured { println 'The project is configured' }
Usually, gradle build is the primary task and the one most used. This task compiles, tests, and assembles the code into a JAR file. The build is started by typing:
> gradle build
Execute the command above to output:
> Configure project : This is executed during configuration phase The project is configured BUILD SUCCESSFUL in 1s 2 actionable tasks: 2 up-to-date
To see the build results, let's look at the build folder which contains sub-folders: classes, distributions, libs, and reports. Typing the Tree / F gives the structure of the build folder:
├───build │ ├───classes │ │ └───java │ │ ├───main │ │ │ └───employee │ │ │ Employee.class │ │ │ EmployeeApp.class │ │ │ │ │ └───test │ │ └───employee │ │ EmployeeAppTest.class │ │ │ ├───distributions │ │ gradle-employee-app.tar │ │ gradle-employee-app.zip │ ├───libs │ │ gradle-employee-app.jar │ │ │ ├───reports │ │ └───tests │ │ └───test │ │ │ index.html │ │ │ │ │ ├───classes │ │ │ employee.EmployeeAppTest.html
As you can see, the classes sub-folder contains two compiled .class files we previously created. The distributions sub-folder contains an archived version of the application jar package. And libs keeps the jar file of our application.
Usually, in reports, there are files that are generated when running JUnit tests.
Now everything is ready to run the Java project by typing gradle run.The result of executing the application on exit:
> Configure project : This is executed during configuration phase The project is configured > Task :run Name: John Email Address: john@baeldung.com Year Of Birth:1978 BUILD SUCCESSFUL in 1s 2 actionable tasks: 1 executed, 1 up-to-date
3.1. Build Using Gradle Wrapper
The Gradle Wrapper is a script that invokes a declared version of Gradle.
First, let's define a wrapper task in the build.gradle file:
task wrapper(type: Wrapper){ gradleVersion = '5.3.1' }
Let's run this task using gradle wrapper from Power Shell:
> Configure project : This is executed during configuration phase The project is configured BUILD SUCCESSFUL in 1s 1 actionable task: 1 executed
Several files will be created under the project folder, including the files under /gradle/wrapper location:
│ gradlew │ gradlew.bat │ ├───gradle │ └───wrapper │ gradle-wrapper.jar │ gradle-wrapper.properties
- gradlew: the shell script used to create Gradle tasks on Linux
- gradlew.bat: a .bat script that Windows users to create Gradle tasks
- gradle-wrapper.jar: a wrapper-executable jar of our application
- gradle-wrapper.properties: properties file for configuring the wrapper
4. Add Java Dependencies and Run a Simple Test
First, in our configuration file, we need to set a remote repository from where we download dependency jars. Most often, these repositories are either mavenCentral() or jcenter(). Let's choose the second one:
repositories { jcenter() }
With our repositories created, we can then specify which dependencies to download. In this example, we are adding Apache Commons and JUnit library. To implement, add testImplementation and testRuntime parts in the dependencies configuration.
It builds on an additional test block:
dependencies { compile group: 'org.apache.commons', name: 'commons-lang3', version: '3.10' testImplementation('junit:junit:4.13') testRuntime('junit:junit:4.13') } test { useJUnit() }
When that's done, let's try the work of JUnit on a simple test. Navigate to the src folder and make the sub-folders for the test:
src> mkdir test/java/employee
Within the last sub-folder, let's create EmployeeAppTest.java:
public class EmployeeAppTest { @Test public void testData() { Employee testEmp = this.getEmployeeTest(); assertEquals(testEmp.name, "John"); assertEquals(testEmp.emailAddress, "john@baeldung.com"); assertEquals(testEmp.yearOfBirth, 1978); } private Employee getEmployeeTest() { Employee employee = new Employee(); employee.name = "John"; employee.emailAddress = "john@baeldung.com"; employee.yearOfBirth = 1978; return employee; } }
Similar to before, let's run a gradle clean test from the command line and the test should pass without issue.
5. Java Project Initialization Using Gradle
In this section, we'll explain the steps for creating and building a Java application that we have gone through so far. The difference is that, this time, we work with the help of the Gradle Build Init Plugin.
Create a new project folder and name it gradle-java-example. Then, switch to that empty project folder and run the init script:
> gradle init
Gradle will ask us with few questions and offer options for creating a project. The first question is what type of project we want to generate:
Select type of project to generate: 1: basic 2: cpp-application 3: cpp-library 4: groovy-application 5: groovy-library 6: java-application 7: java-library 8: kotlin-application 9: kotlin-library 10: scala-library Select build script DSL: 1: groovy 2: kotlin Enter selection [1..10] 6
Select option 6 for the type of project and then first option (groovy) for the build script.
Next, a list of questions appears:
Select test framework: 1: junit 2: testng 3: spock Enter selection (default: junit) [1..3] 1 Project name (default: gradle-java-example): Source package (default: gradle.java.example): employee BUILD SUCCESSFUL in 57m 45s 2 actionable tasks: 2 executed
Here, we select the first option, junit, for the test framework. Select the default name for our project and type “employee” as the name of the source package.
To see the complete directory structure within /src project folders, let's type Tree /F in Power Shell:
├───main │ ├───java │ │ └───employee │ │ App.java │ │ │ └───resources └───test ├───java │ └───employee │ AppTest.java │ └───resources
Finally, if we build the project with gradle run, we get “Hello World” on exit:
> Task :run Hello world. BUILD SUCCESSFUL in 1s 2 actionable tasks: 1 executed, 1 up-to-date
6. Conclusion
In this article, we've presented two ways to create and build a Java application using Gradle. The fact is, we did the manual work and it took time to start compiling and building applications from the command line. In this case, we should pay attention to the import of some required packages and classes if the application uses multiple libraries.
On the other side, the Gradle init script has features that generate a light skeleton of our project, as well as some of the configuration files associated with Gradle.
The source code for this article is available over on GitHub.