Spring Boot Gradle Tutorial

Spring Boot is a powerful framework that simplifies the development of Java applications by providing a set of pre-configured tools and libraries. Gradle, on the other hand, is a build automation tool that streamlines the build process. In this guide, we'll walk through setting up a Spring Boot project with Gradle, creating a simple REST API with a service layer, and testing it using Postman.

What is Spring Boot?

Spring Boot is an extension of the Spring framework that allows developers to create stand-alone, production-grade Spring-based applications that can run with minimal configuration. It provides a set of pre-configured tools and libraries to reduce boilerplate code and simplify the development process.

What is Gradle?

Gradle is an open-source build automation tool designed to be highly customizable and flexible. It automates the building, testing, and deployment of software applications. Gradle supports multi-project builds, incremental builds, and a variety of programming languages and platforms.

Step 1: Install Prerequisites

Before starting, ensure you have the following installed:

  • Java Development Kit (JDK) 21: Download JDK
  • Gradle: Follow the installation steps for your operating system.

Verify Installation

Ensure both Java and Gradle are installed correctly by running:

java -version
gradle -v

Step 2: Initialize a Spring Boot Project

Spring Initializr is a web-based tool provided by the Spring team to create Spring Boot projects. However, you can also create a new project directly using Gradle from the command line.

Using Spring Initializr

  1. Visit Spring Initializr.
  2. Select the following options:
    • Project: Gradle Project
    • Language: Java
    • Spring Boot: 3.2.0 (or the latest stable version)
    • Project Metadata: Fill in Group, Artifact, Name, Description, and Package Name.
    • Packaging: Jar
    • Java: 21
  3. Add dependencies:
    • Spring Web
    • Spring Boot DevTools
    • Spring Data JPA
    • H2 Database (for in-memory database)
  4. Click on "Generate" to download the project zip file.
  5. Extract the zip file to your desired directory.

Using Command Line

Alternatively, you can use the Spring Boot CLI to generate the project. Ensure you have the Spring Boot CLI installed.

spring init --dependencies=web,data-jpa,h2 --java-version=21 --build=gradle my-spring-boot-project

Navigate to the project directory:

cd my-spring-boot-project

Step 3: Explore the Project Structure

After creating the project, your directory structure should look like this:

my-spring-boot-project/
├── build.gradle
├── src/
│   ├── main/
│   │   ├── java/
│   │   │   └── com/
│   │   │       └── example/
│   │   │           └── MySpringBootApplication.java
│   │   ├── resources/
│   │       └── application.properties
│   └── test/
│       ├── java/
│       │   └── com/
│       │       └── example/
│       │           └── MySpringBootApplicationTests.java
│       └── resources/
└── settings.gradle

Step 4: Configure build.gradle

Open the build.gradle file and ensure it is configured correctly with the latest Spring Boot and dependency versions.

Example build.gradle

plugins {
    id 'org.springframework.boot' version '3.2.0'
    id 'io.spring.dependency-management' version '1.1.0'
    id 'java'
}

group = 'com.example'
version = '0.0.1-SNAPSHOT'
sourceCompatibility = '21'

repositories {
    mavenCentral()
}

dependencies {
    implementation 'org.springframework.boot:spring-boot-starter-web'
    implementation 'org.springframework.boot:spring-boot-starter-data-jpa'
    runtimeOnly 'com.h2database:h2'
    testImplementation 'org.springframework.boot:spring-boot-starter-test'
}

test {
    useJUnitPlatform()
}

Step 5: Create a Simple REST Controller

Create a new Java class in src/main/java/com/example named HelloController.java.

Example HelloController.java

package com.example;

import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class HelloController {

    private final HelloService helloService;

    public HelloController(HelloService helloService) {
        this.helloService = helloService;
    }

    @GetMapping("/hello")
    public String hello() {
        return helloService.getHelloMessage();
    }
}

Step 6: Create a Service Layer

Create a new Java class in src/main/java/com/example named HelloService.java.

Example HelloService.java

package com.example;

import org.springframework.stereotype.Service;

@Service
public class HelloService {

    public String getHelloMessage() {
        return "Hello, Spring Boot with Gradle!";
    }
}

Step 7: Run the Application

You can run the Spring Boot application using Gradle. Open a terminal in the project directory and run:

./gradlew bootRun

If everything is set up correctly, you should see the Spring Boot application starting up in the terminal output. Once the application is running, open a web browser and navigate to http://localhost:8080/hello. You should see "Hello, Spring Boot with Gradle!" displayed.

Step 8: Test the API using Postman

  1. Open Postman.
  2. Create a new request.
  3. Set the request type to GET.
  4. Enter the URL: http://localhost:8080/hello.
  5. Click on "Send".

You should see the response "Hello, Spring Boot with Gradle!" in the response body.

Step 9: Create a Simple JPA Entity

Let's create a simple JPA entity to interact with the H2 database. Create a new Java class in src/main/java/com/example named User.java.

Example User.java

package com.example;

import jakarta.persistence.Entity;
import jakarta.persistence.GeneratedValue;
import jakarta.persistence.GenerationType;
import jakarta.persistence.Id;

@Entity
public class User {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;
    private String name;

    // Getters and Setters
}

Step 10: Create a JPA Repository

Create a repository interface to perform CRUD operations on the User entity. Create a new Java interface in src/main/java/com/example named UserRepository.java.

Example UserRepository.java

package com.example;

import org.springframework.data.jpa.repository.JpaRepository;

public interface UserRepository extends JpaRepository<User, Long> {
}

Step 11: Create a CommandLineRunner to Populate Data

Create a new Java class in src/main/java/com/example named DataLoader.java to populate some initial data.

Example DataLoader.java

package com.example;

import org.springframework.boot.CommandLineRunner;
import org.springframework.stereotype.Component;

@Component
public class DataLoader implements CommandLineRunner {

    private final UserRepository userRepository;

    public DataLoader(UserRepository userRepository) {
        this.userRepository = userRepository;
    }

    @Override
    public void run(String... args) throws Exception {
        userRepository.save(new User(null, "John Doe"));
        userRepository.save(new User(null, "Jane Doe"));
    }
}

Step 12: Test the Application

Create a simple test case to verify that the application is working as expected. Create a new Java class in src/test/java/com/example named UserRepositoryTests.java.

Example UserRepositoryTests.java

package com.example;

import static org.assertj.core.api.Assertions.assertThat;

import java.util.List;

import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.orm.jpa.DataJpaTest;

@DataJpaTest
public class UserRepositoryTests {

    @Autowired
    private UserRepository userRepository;

    @Test
    public void testFindAll() {
        List<User> users = userRepository.findAll();
        assertThat(users).hasSize(2);
    }
}

Run the tests using Gradle:

./gradlew test

Conclusion

In this guide, we've covered how to set up a Spring Boot project with Gradle, create a simple REST controller, interact with a database using JPA, add a service layer, and write tests to verify the functionality. We also demonstrated how to test the API using Postman. By following these steps, you should have a solid foundation for building more complex Spring Boot applications using Gradle. For more information, refer to the Spring Boot documentation and the Gradle documentation.

Comments