Lädt...


🔧 Build Your First Spring Boot REST Application with Gradle


Nachrichtenbereich: 🔧 Programmierung
🔗 Quelle: dev.to

Creating Your First REST Application with Spring Boot and Gradle

Introduction

In this tutorial, we will create a simple RESTful web service using Spring Boot and Gradle. Spring Boot makes it easy to create stand-alone, production-grade Spring-based applications, and Gradle is a powerful build tool that simplifies the build process.

Prerequisites

  • Java Development Kit (JDK) installed
  • Gradle installed
  • Basic understanding of Java and Spring concepts

Step 1: Set Up the Project

Create a new directory for your project and navigate to it in the terminal or command prompt.

mkdir spring-boot-rest-gradle
cd spring-boot-rest-gradle

Step 2: Create a Spring Boot Project

Create a new file named build.gradle and add the following content:

plugins {
    id 'org.springframework.boot' version '2.6.3'
    id 'io.spring.dependency-management' version '1.0.11.RELEASE'
    id 'java'
}

group = 'com.example'
version = '1.0-SNAPSHOT'
sourceCompatibility = '11'

repositories {
    mavenCentral()
}

dependencies {
    implementation 'org.springframework.boot:spring-boot-starter-web'
    testImplementation 'org.springframework.boot:spring-boot-starter-test'
}

test {
    useJUnitPlatform()
}

This sets up a basic Spring Boot project with the necessary dependencies.

Step 3: Create a REST Controller

Create a new file named HelloController.java in the src/main/java/com/example directory with the following content:

import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;

@RestController
@RequestMapping("/api")
public class HelloController {

    private final List<String> messages = new ArrayList<>();

    @GetMapping("/hello")
    public String sayHello() {
        return "Hello, Spring Boot!";
    }

    @GetMapping("/messages")
    public List<String> getMessages() {
        return messages;
    }

    @PostMapping("/messages")
    public String addMessage(@RequestBody String message) {
        messages.add(message);
        return "Message added: " + message;
    }

    @PutMapping("/messages/{index}")
    public String updateMessage(@PathVariable int index, @RequestBody String updatedMessage) {
        if (index < messages.size()) {
            messages.set(index, updatedMessage);
            return "Message updated at index " + index + ": " + updatedMessage;
        } else {
            return "Invalid index";
        }
    }

    @DeleteMapping("/messages/{index}")
    public String deleteMessage(@PathVariable int index) {
        if (index < messages.size()) {
            String removedMessage = messages.remove(index);
            return "Message removed at index " + index + ": " + removedMessage;
        } else {
            return "Invalid index";
        }
    }
}

This defines a REST controller with endpoints for GET, POST, PUT, and DELETE operations on a simple list of messages.

Step 4: Run the Application

Open a terminal or command prompt and run the following command:

./gradlew bootRun

Visit http://localhost:8080/api/hello in your browser to check the initial endpoint. You can use tools like curl, Postman, or any REST client to test the other endpoints.

Step 5: Write Test Cases

Create a new file named HelloControllerTest.java in the src/test/java/com/example directory with the following content:

import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.BeforeEach;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.http.MediaType;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.request.MockMvcRequestBuilders;
import org.springframework.test.web.servlet.result.MockMvcResultMatchers;

import static org.hamcrest.Matchers.hasSize;
import static org.hamcrest.Matchers.is;

@SpringBootTest
@AutoConfigureMockMvc
public class HelloControllerTest {

    @Autowired
    private MockMvc mockMvc;

    @BeforeEach
    public void setUp() {
        // Clear messages before each test
        // This ensures a clean state for each test
        // Alternatively, you could use a test database or mock data
        // depending on your requirements
        HelloController messagesController = new HelloController();
        messagesController.getMessages().clear();
    }

    @Test
    public void testSayHello() throws Exception {
        mockMvc.perform(MockMvcRequestBuilders.get("/api/hello"))
                .andExpect(MockMvcResultMatchers.status().isOk())
                .andExpect(MockMvcResultMatchers.content().string("Hello, Spring Boot!"));
    }

    @Test
    public void testGetMessages() throws Exception {
        mockMvc.perform(MockMvcRequestBuilders.get("/api/messages"))
                .andExpect(MockMvcResultMatchers.status().isOk())
                .andExpect(MockMvcResultMatchers.jsonPath("$", hasSize(0)));
    }

    @Test
    public void testAddMessage() throws Exception {
        mockMvc.perform(MockMvcRequestBuilders.post("/api/messages")
                .contentType(MediaType.APPLICATION_JSON)
                .content("\"Test Message\""))
                .andExpect(MockMvcResultMatchers.status().isOk())
                .andExpect(MockMvcResultMatchers.content().string("Message added: Test Message"));
    }

    @Test
    public void testUpdateMessage() throws Exception {
        mockMvc.perform(MockMvcRequestBuilders.post("/api/messages")
                .contentType(MediaType.APPLICATION_JSON)
                .content("\"Initial Message\""));

        mockMvc.perform(MockMvcRequestBuilders.put("/api/messages/0")
                .contentType(MediaType.APPLICATION_JSON)
                .content("\"Updated Message\""))
                .andExpect(MockMvcResultMatchers.status().isOk())
                .andExpect(MockMvcResultMatchers.content().string("Message updated at index 0: Updated Message"));
    }

    @Test
    public void testDeleteMessage() throws Exception {
        mockMvc.perform(MockMvcRequestBuilders.post("/api/messages")
                .contentType(MediaType.APPLICATION_JSON)
                .content("\"Message to Delete\""));

        mockMvc.perform(MockMvcRequestBuilders.delete("/api/messages/0"))
                .andExpect(MockMvcResultMatchers.status().isOk())
                .andExpect(MockMvcResultMatchers.content().string("Message removed at index 0: Message to Delete"));
    }
}

These test cases use Spring Boot's testing features to simulate HTTP requests and verify the behavior of the REST controller.

Step 6: Run Tests

Open a terminal or command prompt and run the following command to execute the tests:

./gradlew test

Review the test results to ensure that all tests pass successfully.

Conclusion

Congratulations! You have successfully created a basic RESTful web service with CRUD operations using Spring Boot and Gradle. This tutorial covered the implementation of endpoints for GET, POST, PUT, and DELETE operations along with corresponding test cases.

...

🔧 Build Your First Spring Boot REST Application with Gradle


📈 67.55 Punkte
🔧 Programmierung

🔧 Build a Spring Boot REST Application With Gradle


📈 58.54 Punkte
🔧 Programmierung

🔧 Spring Boot 3 application on AWS Lambda - Part 9 Develop application with Spring Cloud Function AWS


📈 39.41 Punkte
🔧 Programmierung

📰 Zwei Probleme in gradle-bootstrap und gradle (SUSE)


📈 39.06 Punkte
📰 IT Security Nachrichten

🕵️ Gradle gradle-enterprise-test-distribution-agent Registration pathname traversal


📈 39.06 Punkte
🕵️ Sicherheitslücken

🔧 Master REST API Development and Streamline Data Access with Spring Boot and Spring Data JPA


📈 37.59 Punkte
🔧 Programmierung

🔧 Spring Boot 3 Integrate QueryDsl with Gradle


📈 37.41 Punkte
🔧 Programmierung

🔧 Spring vs Spring MVC vs Spring Boot: A Detailed Comparison for Java Developers


📈 37.32 Punkte
🔧 Programmierung

📰 software-architektur.tv: GraalVM mit Spring Native, Spring Boot und Spring Cloud


📈 37.32 Punkte
📰 IT Nachrichten

🔧 Building Your First Spring Boot App: A Complete Guide to MVC Architecture and REST Controllers


📈 36.88 Punkte
🔧 Programmierung

🔧 How to Use Spring Profiles in Your Spring Boot Application


📈 36.76 Punkte
🔧 Programmierung

🔧 How to Use Spring Boot Eureka Server in Spring Boot 3.3.0+


📈 35.76 Punkte
🔧 Programmierung

🔧 Spring Boot 3 application on AWS Lambda - Part 8 Introduction to Spring Cloud Function


📈 33.5 Punkte
🔧 Programmierung

🔧 Build CRUD RESTful API Using Spring Boot 3, Spring Data JPA, Hibernate, and MySQL Database


📈 32.84 Punkte
🔧 Programmierung

🔧 Master Spring Boot and Spring Security: Build a Shopping Cart Backend


📈 32.84 Punkte
🔧 Programmierung

🔧 Build a Shopping Cart Backend with Spring Boot and Spring Security


📈 32.84 Punkte
🔧 Programmierung

🔧 Write your first Spring Boot application


📈 32.79 Punkte
🔧 Programmierung

🔧 Locking Down Your Spring Boot Apps: A Deep Dive into Spring Security


📈 30.85 Punkte
🔧 Programmierung

🕵️ Pivotal Spring Data REST bis 2.5.11/2.6.6/3.0 RC2 REST Server JSON Data Code erweiterte Rechte


📈 29.7 Punkte
🕵️ Sicherheitslücken

🔧 Spring Boot 3 application on AWS Lambda - Part 6 Develop application with AWS Lambda Web Adapter


📈 29.69 Punkte
🔧 Programmierung

🔧 Spring Boot 3 application on AWS Lambda - Part 3 Develop application with AWS Serverless Java Container


📈 29.69 Punkte
🔧 Programmierung

🔧 Build native image from Spring Boot Application with GraalVM builder


📈 29.02 Punkte
🔧 Programmierung

🔧 Multi-Modules Architecture: Dependency Management _ Build your own gradle plugin


📈 28.02 Punkte
🔧 Programmierung

📰 Preparing your Gradle build for package visibility in Android 11


📈 28.02 Punkte
🤖 Android Tipps

🔧 🚀 Demystifying APIs and REST with Spring Boot: Crafting Product Services Made Easy🚀


📈 27.87 Punkte
🔧 Programmierung

🔧 Getting Started With Boot Spring 3.2.0: Building a Hello World REST API With NoSQL Integration


📈 27.87 Punkte
🔧 Programmierung

📰 heise+ | Spring Boot: Aufbau und Funktion einer Anwendung am Beispiel eines REST-Service


📈 27.87 Punkte
📰 IT Nachrichten

🔧 Kotlin CRUD Rest Api using Spring Boot, Hibernate, Postgres, Docker and Docker Compose


📈 27.87 Punkte
🔧 Programmierung

🔧 Java CRUD Rest API using Spring Boot, Hibernate, Postgres, Docker and Docker Compose


📈 27.87 Punkte
🔧 Programmierung

🔧 Mastering Spring Boot MVC and REST APIs: A Comprehensive Guide


📈 27.87 Punkte
🔧 Programmierung

matomo