eBook – Guide Spring Cloud – NPI EA (cat=Spring Cloud)
announcement - icon

Let's get started with a Microservice Architecture with Spring Cloud:

>> Join Pro and download the eBook

eBook – Mockito – NPI EA (tag = Mockito)
announcement - icon

Mocking is an essential part of unit testing, and the Mockito library makes it easy to write clean and intuitive unit tests for your Java code.

Get started with mocking and improve your application tests using our Mockito guide:

Download the eBook

eBook – Java Concurrency – NPI EA (cat=Java Concurrency)
announcement - icon

Handling concurrency in an application can be a tricky process with many potential pitfalls. A solid grasp of the fundamentals will go a long way to help minimize these issues.

Get started with understanding multi-threaded applications with our Java Concurrency guide:

>> Download the eBook

eBook – Reactive – NPI EA (cat=Reactive)
announcement - icon

Spring 5 added support for reactive programming with the Spring WebFlux module, which has been improved upon ever since. Get started with the Reactor project basics and reactive programming in Spring Boot:

>> Join Pro and download the eBook

eBook – Java Streams – NPI EA (cat=Java Streams)
announcement - icon

Since its introduction in Java 8, the Stream API has become a staple of Java development. The basic operations like iterating, filtering, mapping sequences of elements are deceptively simple to use.

But these can also be overused and fall into some common pitfalls.

To get a better understanding on how Streams work and how to combine them with other language features, check out our guide to Java Streams:

>> Join Pro and download the eBook

eBook – Jackson – NPI EA (cat=Jackson)
announcement - icon

Do JSON right with Jackson

Download the E-book

eBook – HTTP Client – NPI EA (cat=Http Client-Side)
announcement - icon

Get the most out of the Apache HTTP Client

Download the E-book

eBook – Maven – NPI EA (cat = Maven)
announcement - icon

Get Started with Apache Maven:

Download the E-book

eBook – Persistence – NPI EA (cat=Persistence)
announcement - icon

Working on getting your persistence layer right with Spring?

Explore the eBook

eBook – RwS – NPI EA (cat=Spring MVC)
announcement - icon

Building a REST API with Spring?

Download the E-book

Course – LS – NPI EA (cat=Jackson)
announcement - icon

Get started with Spring and Spring Boot, through the Learn Spring course:

>> LEARN SPRING
Course – RWSB – NPI EA (cat=REST)
announcement - icon

Explore Spring Boot 3 and Spring 6 in-depth through building a full REST API with the framework:

>> The New “REST With Spring Boot”

Course – LSS – NPI EA (cat=Spring Security)
announcement - icon

Yes, Spring Security can be complex, from the more advanced functionality within the Core to the deep OAuth support in the framework.

I built the security material as two full courses - Core and OAuth, to get practical with these more complex scenarios. We explore when and how to use each feature and code through it on the backing project.

You can explore the course here:

>> Learn Spring Security

Course – LSD – NPI EA (tag=Spring Data JPA)
announcement - icon

Spring Data JPA is a great way to handle the complexity of JPA with the powerful simplicity of Spring Boot.

Get started with Spring Data JPA through the guided reference course:

>> CHECK OUT THE COURSE

Partner – Moderne – NPI EA (cat=Spring Boot)
announcement - icon

Refactor Java code safely — and automatically — with OpenRewrite.

Refactoring big codebases by hand is slow, risky, and easy to put off. That’s where OpenRewrite comes in. The open-source framework for large-scale, automated code transformations helps teams modernize safely and consistently.

Each month, the creators and maintainers of OpenRewrite at Moderne run live, hands-on training sessions — one for newcomers and one for experienced users. You’ll see how recipes work, how to apply them across projects, and how to modernize code with confidence.

Join the next session, bring your questions, and learn how to automate the kind of work that usually eats your sprint time.

Course – LJB – NPI EA (cat = Core Java)
announcement - icon

Code your way through and build up a solid, practical foundation of Java:

>> Learn Java Basics

Partner – LambdaTest – NPI EA (cat= Testing)
announcement - icon

Distributed systems often come with complex challenges such as service-to-service communication, state management, asynchronous messaging, security, and more.

Dapr (Distributed Application Runtime) provides a set of APIs and building blocks to address these challenges, abstracting away infrastructure so we can focus on business logic.

In this tutorial, we'll focus on Dapr's pub/sub API for message brokering. Using its Spring Boot integration, we'll simplify the creation of a loosely coupled, portable, and easily testable pub/sub messaging system:

>> Flexible Pub/Sub Messaging With Spring Boot and Dapr

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 = "[email protected]";
        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 the 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 the Application Plugin:

plugins {
    id 'application'
}

Then, 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: [email protected]
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.12.0'
    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, "[email protected]");
        assertEquals(testEmp.yearOfBirth, 1978);
    }

    private Employee getEmployeeTest() {

        Employee employee = new Employee();
        employee.name = "John";
        employee.emailAddress = "[email protected]";
        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 code backing this article is available on GitHub. Once you're logged in as a Baeldung Pro Member, start learning and coding on the project.
Baeldung Pro – NPI EA (cat = Baeldung)
announcement - icon

Baeldung Pro comes with both absolutely No-Ads as well as finally with Dark Mode, for a clean learning experience:

>> Explore a clean Baeldung

Once the early-adopter seats are all used, the price will go up and stay at $33/year.

eBook – HTTP Client – NPI EA (cat=HTTP Client-Side)
announcement - icon

The Apache HTTP Client is a very robust library, suitable for both simple and advanced use cases when testing HTTP endpoints. Check out our guide covering basic request and response handling, as well as security, cookies, timeouts, and more:

>> Download the eBook

eBook – Java Concurrency – NPI EA (cat=Java Concurrency)
announcement - icon

Handling concurrency in an application can be a tricky process with many potential pitfalls. A solid grasp of the fundamentals will go a long way to help minimize these issues.

Get started with understanding multi-threaded applications with our Java Concurrency guide:

>> Download the eBook

eBook – Java Streams – NPI EA (cat=Java Streams)
announcement - icon

Since its introduction in Java 8, the Stream API has become a staple of Java development. The basic operations like iterating, filtering, mapping sequences of elements are deceptively simple to use.

But these can also be overused and fall into some common pitfalls.

To get a better understanding on how Streams work and how to combine them with other language features, check out our guide to Java Streams:

>> Join Pro and download the eBook

eBook – Persistence – NPI EA (cat=Persistence)
announcement - icon

Working on getting your persistence layer right with Spring?

Explore the eBook

Course – LS – NPI EA (cat=REST)

announcement - icon

Get started with Spring Boot and with core Spring, through the Learn Spring course:

>> CHECK OUT THE COURSE

Partner – Moderne – NPI EA (tag=Refactoring)
announcement - icon

Modern Java teams move fast — but codebases don’t always keep up. Frameworks change, dependencies drift, and tech debt builds until it starts to drag on delivery. OpenRewrite was built to fix that: an open-source refactoring engine that automates repetitive code changes while keeping developer intent intact.

The monthly training series, led by the creators and maintainers of OpenRewrite at Moderne, walks through real-world migrations and modernization patterns. Whether you’re new to recipes or ready to write your own, you’ll learn practical ways to refactor safely and at scale.

If you’ve ever wished refactoring felt as natural — and as fast — as writing code, this is a good place to start.

eBook Jackson – NPI EA – 3 (cat = Jackson)