Spring Boot Backend Development Course, Exploring Spring Boot Project Directory Structure

Spring Boot is a framework that helps you easily develop Java-based applications. Recently, many companies and developers have chosen Spring Boot, thanks to various advantages such as rapid prototyping, convenient configuration, and powerful features. In this tutorial, we will explain the project directory structure during the backend development process using Spring Boot, detailing the role and usage of each directory.

What is Spring Boot?

Spring Boot is an open-source framework based on the Spring framework that provides features that help developers build applications more quickly, easily, and efficiently. One of the main features of Spring Boot is convention-over-configuration. This allows developers to run their applications with minimal configuration. Additionally, it provides various starters that make it easy to add the required libraries and settings.

Spring Boot Project Structure

The structure of a Spring Boot project is similar to that of a traditional Java project but includes a few unique directories and files. The basic project structure created using Spring Boot is as follows:

project-root/
│
├── src/
│   ├── main/
│   │   ├── java/
│   │   │   └── com/
│   │   │       └── example/
│   │   │           └── demo/
│   │   ├── resources/
│   │   │   └── application.properties
│   │   └── webapp/
│   └── test/
│       └── java/
└── pom.xml

1. src/main/java

This directory contains the Java code for the application. The package structure is usually designed based on domain and functionality, typically including packages for domain models, services, controllers, and repositories. For example:

com/
└── example/
    └── demo/
        ├── controller/
        ├── service/
        ├── repository/
        └── model/

2. src/main/resources

This directory contains configuration files and static resources for the application. The most important file is application.properties or application.yml, which contains various settings that control the behavior of the application. This includes database connection information, server port, logging settings, etc.

application.properties
spring.datasource.url=jdbc:mysql://localhost:3306/mydb
spring.datasource.username=root
spring.datasource.password=secret

3. src/test/java

This directory contains Java code for unit and integration tests. Spring Boot can easily integrate with various testing frameworks like JUnit and Mockito. By designing and executing tests in this space, you can improve the stability of the application.

4. pom.xml or build.gradle

A Spring Boot application can use either Maven or Gradle as a build tool. This file defines the project’s dependencies and build settings. If using Maven, here’s an example:


    4.0.0
    com.example
    demo
    0.0.1-SNAPSHOT
    jar
    demo
    Demo project for Spring Boot
    
        17
    
    
        
            org.springframework.boot
            spring-boot-starter
        
        
            org.springframework.boot
            spring-boot-starter-test
            test
        
    

Project Example: Creating a Simple REST API

Now, let’s create a simple REST API using Spring Boot. We will create the necessary directories and files and explain their roles.

1. Create Model Class

First, we will create a model class to be used in the application. For example, we will create a Product class. This class represents the information of a product.

package com.example.demo.model;

public class Product {
    private Long id;
    private String name;
    private double price;

    // Getters and setters
}

2. Create Repository Interface

Next, we create a repository interface for interacting with the database. We can easily set up the repository using Spring Data JPA.

package com.example.demo.repository;

import com.example.demo.model.Product;
import org.springframework.data.jpa.repository.JpaRepository;

public interface ProductRepository extends JpaRepository {
}

3. Create Service Class

We add a service class to implement business logic. This class will handle CRUD (Create, Read, Update, Delete) operations for products.

package com.example.demo.service;

import com.example.demo.model.Product;
import com.example.demo.repository.ProductRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class ProductService {
    @Autowired
    private ProductRepository productRepository;

    public List getAllProducts() {
        return productRepository.findAll();
    }

    public Product getProductById(Long id) {
        return productRepository.findById(id).orElse(null);
    }

    public void createProduct(Product product) {
        productRepository.save(product);
    }

    public void updateProduct(Long id, Product product) {
        Product existingProduct = productRepository.findById(id).orElse(null);
        if (existingProduct != null) {
            existingProduct.setName(product.getName());
            existingProduct.setPrice(product.getPrice());
            productRepository.save(existingProduct);
        }
    }

    public void deleteProduct(Long id) {
        productRepository.deleteById(id);
    }
}

4. Create Controller Class

We create a controller class to handle HTTP requests. This class defines the endpoints of the REST API.

package com.example.demo.controller;

import com.example.demo.model.Product;
import com.example.demo.service.ProductService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/api/products")
public class ProductController {
    @Autowired
    private ProductService productService;

    @GetMapping
    public List getAllProducts() {
        return productService.getAllProducts();
    }

    @GetMapping("/{id}")
    public ResponseEntity getProductById(@PathVariable Long id) {
        Product product = productService.getProductById(id);
        if (product == null) {
            return new ResponseEntity<>(HttpStatus.NOT_FOUND);
        }
        return new ResponseEntity<>(product, HttpStatus.OK);
    }

    @PostMapping
    public ResponseEntity createProduct(@RequestBody Product product) {
        productService.createProduct(product);
        return new ResponseEntity<>(HttpStatus.CREATED);
    }

    @PutMapping("/{id}")
    public ResponseEntity updateProduct(@PathVariable Long id, @RequestBody Product product) {
        productService.updateProduct(id, product);
        return new ResponseEntity<>(HttpStatus.NO_CONTENT);
    }

    @DeleteMapping("/{id}")
    public ResponseEntity deleteProduct(@PathVariable Long id) {
        productService.deleteProduct(id);
        return new ResponseEntity<>(HttpStatus.NO_CONTENT);
    }
}

Building and Running Spring Boot

Now that all components are ready, let’s build and run the application. Spring Boot makes it very easy to run applications using an embedded server. You can start the application with the following command:

./mvnw spring-boot:run

Once the application starts, you can send a GET request to the http://localhost:8080/api/products endpoint using a browser or an API testing tool (like Postman).

Conclusion

In this tutorial, we learned the basics of backend development using Spring Boot. We understood the project directory structure and implemented a simple REST API, experiencing the charm of Spring Boot. In the future, we can explore more complex features, security, database integration, frontend integration, and various topics.

Spring Boot is a powerful tool, and building a solid foundation will greatly help in developing more complex applications. If you have more questions or curiosities about your development journey, please feel free to leave a comment!

Spring Boot Backend Development Course, Exploring Spring Boot Starter

Spring Boot is a framework that helps build Java-based web applications quickly and easily. In this course, we will cover the core concepts of Spring Boot and how to get started developing backend applications using Spring Boot starters.

1. What is Spring Boot?

Spring Boot is an extension of the Spring Framework, but it has a ‘convention over configuration’ structure, allowing complex Spring applications to be created easily with minimal configuration. With Spring Boot, anyone can start and deploy applications with ease.

1.1 Advantages of Spring Boot

  • Fast development cycles
  • Minimal configuration
  • Built-in web server support
  • Auto-configuration
  • Creating an environment that allows focus on business logic

2. What are Spring Boot Starters?

Spring Boot starters are a collection of various libraries that make it easy to create Spring Boot applications. Each starter comprehensively manages the various dependencies required for specific functionalities.

2.1 Types of Starters

  • spring-boot-starter-web: A starter for building web applications, which includes Spring MVC and Tomcat.
  • spring-boot-starter-data-jpa: Simplifies database access using JPA.
  • spring-boot-starter-security: A starter for security that supports authentication and authorization.
  • spring-boot-starter-test: A starter for testing, including testing libraries like JUnit and Mockito.
  • spring-boot-starter-actuator: Adds functionality to monitor the application’s status and metrics.

3. Using Spring Boot Starter

3.1 Adding Dependencies

To use Spring Boot starters, you first need to add dependencies using Maven or Gradle. For example, if you are using Maven, add the following dependency in your pom.xml file.



    org.springframework.boot
    spring-boot-starter-web

3.2 Creating a Simple Web Application

Now, let’s create a simple web application using Spring Boot starters. Below is an example of a basic REST controller.


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

@RestController
public class HelloController {

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

By sending a request to the /hello path using the code above, a simple REST API is created that returns the message “Hello, Spring Boot!”.

3.3 Running the Application

Once the application is set up, you can start the server by running the main application class. Calling the SpringApplication.run() method will run the embedded Tomcat server.


import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class Application {

    public static void main(String[] args) {
        SpringApplication.run(Application.class, args);
    }
}

4. Use Cases for Spring Boot Starters

We will cover various real-world use cases utilizing Spring Boot starters. In this process, we will explain how each starter is used and how actual business logic is structured.

4.1 Creating a CRUD Application

Let’s create a simple CRUD (Create, Read, Update, Delete) application using the Spring Boot Data JPA starter. You can set up a connection to the database and define entities to manage data.


// Entity definition
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;

@Entity
public class User {
    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private Long id;
    private String name;
    private String email;

    // getters and setters
}

4.2 Implementing the Service Layer

By implementing the service layer, we can process business logic and separate the controller from the database access layer.


import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class UserService {
    @Autowired
    private UserRepository userRepository;

    public List findAllUsers() {
        return userRepository.findAll();
    }

    public User saveUser(User user) {
        return userRepository.save(user);
    }

    // Other necessary methods
}

5. Conclusion and Next Steps

In this course, we explored the basic concepts of Spring Boot and Spring Boot starters, as well as how to create a simple web application. If you have learned how to use Spring Boot, it is now time to consider more complex business logic and deployment environments.

Additionally, Spring Boot allows you to extend functionality through various starters. Based on what you’ve learned in this course, we hope you will engage in a variety of projects.

Thank you!

Spring Boot Backend Development Course, Understanding the Spring Boot Request-Response Process at Once

Understanding the Spring Boot Request-Response Process in One Go

Hello, everyone! Today, we will delve deeply into one of the most important elements in backend development using Spring Boot, which is the request-response process. Spring Boot reduces the complexity of the traditional Spring framework and provides developers with a more intuitive and faster development environment. Understanding the flow of requests and responses in web applications is key to successful application development, so today’s lecture will focus on how to understand and utilize this.

1. Introduction to Spring Boot

Spring Boot is a lightweight framework built on the Spring framework, aimed at rapid development and deployment. It offers simpler configuration compared to traditional Spring and provides an auto-configuration feature that helps set up complex application structures with minimal code.

2. Understanding the Request-Response Structure

The request-response flow in Spring Boot involves interaction between clients and servers. The client sends an HTTP request to the server, and the server processes this request and returns an appropriate HTTP response. This process can generally be divided into the following steps:

2.1 Client Request

The client sends an HTTP request to call a REST API. This request includes information such as the method (GET, POST, PUT, DELETE, etc.), request URL, headers, and body. For example, when a user clicks a button on a web page, the browser sends a GET request to the URL of the corresponding API.

2.2 Dispatcher Servlet

The requests of a Spring Boot application are first passed to the Dispatcher Servlet. This servlet is a key component of Spring MVC that routes the client’s requests to the appropriate handler. It uses annotation-based mapping to find a handler capable of processing the request.

2.3 Handler Method

Once the Dispatcher Servlet finds the appropriate handler, the corresponding handler method is called. This method processes the request and performs business logic. It may interact with a database or communicate with other services. Handler methods are typically defined with the @RestController or @Controller annotation.

2.4 Response Generation

After the handler method completes processing the request, it returns a response object containing the results. This object is converted to an HTTP response by Spring MVC and sent to the client. At this stage, it can be transformed into formats like JSON or XML for return.

2.5 Client Response

The client interprets the HTTP response received from the server and performs appropriate actions. This includes updating the user interface (UI), displaying data, handling error messages, etc.

3. Example of the Request-Response Process

Now, let’s create a simple web application using Spring Boot and implement the request-response process in actual code.

3.1 Adding Dependencies

First, we add the necessary dependencies to the pom.xml file. By adding the most basic Spring Boot starter web dependency, we can build a RESTful API.

<dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-web</artifactId>
    </dependency>

3.2 Creating a Simple Model

Now we will create a simple model class called User.

public class User {
        private Long id;
        private String username;
        private String email;

        // Getters and Setters
    }

3.3 Implementing the Controller

Next, we will implement the controller class that will provide the REST API.

@RestController
    @RequestMapping("/api/users")
    public class UserController {

        @GetMapping("/{id}")
        public ResponseEntity getUserById(@PathVariable Long id) {
            User user = userService.findUserById(id); // Logic to find user
            return ResponseEntity.ok(user);
        }
        
        @PostMapping
        public ResponseEntity createUser(@RequestBody User user) {
            User createdUser = userService.createUser(user); // Logic to create user
            return ResponseEntity.status(HttpStatus.CREATED).body(createdUser);
        }
    }

3.4 Implementing the Service

In the service class, we handle the business logic related to users.

@Service
    public class UserService {

        public User findUserById(Long id) {
            // Logic to find user (DB integration, etc.)
        }
        
        public User createUser(User user) {
            // Logic to create user (DB integration, etc.)
        }
    }

4. Testing and Validation

You can use tools like Postman to test whether the API you have written works properly. Try retrieving data with a GET request and creating a new user with a POST request. This will help you clearly understand how the request-response process works.

5. Conclusion

I hope this course has helped you gain a deep understanding of the request-response process in Spring Boot. This process is essential knowledge in backend development, and I encourage you to gain more experience through actual development. We plan to cover more Spring Boot-related topics in the future, so I look forward to your interest!

6. Additional Resources

If you would like to learn more about Spring Boot and related topics, please refer to the following resources:

Spring Boot Backend Development Course, Spring Boot 3 and Testing

In modern software development, rapid deployment and flexibility are very important. To meet these requirements, Spring Boot has gained popularity among many developers. In this article, we will take a detailed look at the main features of Spring Boot 3 and effective testing methods.

1. Understanding Spring Boot

Spring Boot is a development tool based on the Spring Framework, designed to make it easier to set up and run Spring applications. By using Spring Boot, you can avoid complex XML configurations and set up your application with simple annotations.

1.1 Features of Spring Boot

  • Automatic Configuration: Spring Boot automatically configures the necessary settings, reducing development time.
  • Standalone: Spring Boot projects are packaged as standalone JAR files, making them easy to deploy.
  • Simplified Configuration: Reduces complex XML configurations and allows for simple setups using annotations.
  • Simple Customization: Allows for easy customization of application behavior through various properties.

2. New Features of Spring Boot 3

Spring Boot 3 has introduced several new features and improvements compared to previous versions. In this section, we will look at the main features.

2.1 Support for Java 17

Spring Boot 3 natively supports Java 17. It allows you to leverage the new features and improvements of Java 17 to write safer and more efficient code.

2.2 New Dependency Management

Spring Boot 3 provides a new mechanism to manage various dependencies more easily, helping developers select libraries and adjust versions as needed.

2.3 Improved Performance

Spring Boot 3 has optimized its internal engine to improve application kill chain performance. As a result, you can expect faster boot times and better response speeds.

3. Developing Backend with Spring Boot 3

Now, let’s take a look at the process of creating a simple CRUD (Create, Read, Update, Delete) application using Spring Boot. We will proceed step by step.

3.1 Project Setup

Let’s configure the necessary settings to start a Spring Boot application. First, we will create a new project using Spring Initializr. Select required dependencies such as ‘Spring Web’, ‘Spring Data JPA’, and ‘H2 Database’.

3.2 Application Structure

The structure of the generated project is as follows.

src
└── main
    ├── java
    │   └── com
    │       └── example
    │           └── demo
    │               ├── DemoApplication.java
    │               ├── controller
    │               ├── model
    │               └── repository
    └── resources
        └── application.properties

3.3 Creating Model Class

First, we will create an entity class to be stored in the database. For example, let’s create a model class called ‘User’.

package com.example.demo.model;

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

@Entity
public class User {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;
    private String name;
    private String email;

    // Getters and setters
}

3.4 Creating Repository Interface

We will create a repository interface to interact with the database using Spring Data JPA.

package com.example.demo.repository;

import com.example.demo.model.User;
import org.springframework.data.jpa.repository.JpaRepository;

public interface UserRepository extends JpaRepository {
}

3.5 Creating Controller Class

We will write a controller class to provide RESTful APIs.

package com.example.demo.controller;

import com.example.demo.model.User;
import com.example.demo.repository.UserRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/api/users")
public class UserController {

    @Autowired
    private UserRepository userRepository;

    @GetMapping
    public List getAllUsers() {
        return userRepository.findAll();
    }

    @PostMapping
    public User createUser(@RequestBody User user) {
        return userRepository.save(user);
    }
    
    // Add methods for updating and deleting users
}

3.6 Running the Application

Once all configurations are complete, please run the application. You can use the command ./mvnw spring-boot:run to execute it.

4. Spring Boot Testing

Testing is very important during the application development process. Spring Boot provides various tools and frameworks for testing.

4.1 Types of Testing in Spring Boot

Spring Boot supports several types of testing:

  • Unit Test: Validates the behavior of individual methods or classes.
  • Integration Test: Validates whether multiple components work together.
  • End-to-End Test: Validates that the entire functionality of the application works correctly.

4.2 Writing Unit Tests

Let’s write a simple unit test. We will test the UserService class using JUnit 5 and Mockito.

package com.example.demo.service;

import com.example.demo.model.User;
import com.example.demo.repository.UserRepository;
import org.junit.jupiter.api.Test;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.MockitoAnnotations;

import static org.mockito.Mockito.when;
import static org.junit.jupiter.api.Assertions.assertEquals;

public class UserServiceTest {

    @InjectMocks
    private UserService userService;

    @Mock
    private UserRepository userRepository;

    public UserServiceTest() {
        MockitoAnnotations.openMocks(this);
    }

    @Test
    void testCreateUser() {
        User user = new User();
        user.setName("John Doe");
        user.setEmail("john@example.com");

        when(userRepository.save(user)).thenReturn(user);

        User createdUser = userService.createUser(user);
        assertEquals("John Doe", createdUser.getName());
    }
}

4.3 Writing Integration Tests

Let’s also look at how to perform integration testing in Spring Boot. We can use the @SpringBootTest annotation for this.

package com.example.demo;

import org.junit.jupiter.api.Test;
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.test.web.servlet.MockMvc;

import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;

@SpringBootTest
@AutoConfigureMockMvc
public class UserControllerTest {

    @Autowired
    private MockMvc mockMvc;

    @Test
    public void testCreateUser() throws Exception {
        String json = "{\"name\":\"John Doe\", \"email\":\"john@example.com\"}";

        mockMvc.perform(post("/api/users")
                .contentType("application/json")
                .content(json))
                .andExpect(status().isCreated());
    }
}

5. Conclusion

In this opportunity, we learned about the key features and testing methods of Spring Boot 3. Spring Boot is a powerful tool that helps developers quickly build and reliably operate applications. It is important to effectively develop backend systems using various features and improve the quality of applications through testing.

We hope you continue to gain experience by working on more projects using Spring Boot and grow into a better developer.

Spring Boot Backend Development Course, Spring Boot 3 and Java Version

Hello! Today, we will conduct an in-depth course on backend development using Spring Boot. Spring Boot is a Java-based framework that provides a platform for developing web applications quickly and easily. This course focuses on Spring Boot 3 and the latest version of Java.

1. What is Spring Boot?

Spring Boot is an extension of the Spring Framework. The Spring Framework is a powerful development tool for applications developed in Java, but its configuration and initialization can be complex. Spring Boot was created to address these issues and provides the following key features:

  • Auto Configuration: You can start your application without complex Spring configurations.
  • Standalone Applications: It provides applications that can run independently through an embedded server.
  • Production Ready: It includes various features for monitoring and management.

2. Key Changes in Spring Boot 3

Spring Boot 3 is based on Spring Framework 6 and includes several new features and improvements. Key changes include:

  • JDK 17 Required: Spring Boot 3 requires a minimum of JDK 17, allowing the use of new Java features.
  • HTTP/2 Support: Supports HTTP/2 by default for better performance.
  • Jakarta EE 9 Support: The package namespace has changed from `javax` to `jakarta`.

3. Setting Up the Development Environment

To develop with Spring Boot, you need to set up your development environment. Please follow the steps below.

1. Install JDK: Install OpenJDK 17 or higher.
2. Install an IDE: Choose and install an IDE such as IntelliJ IDEA or Eclipse.
3. Install Maven or Gradle: Use Maven or Gradle to manage dependencies.

3.1 Install JDK

The JDK is a Java development tool; download and install the latest version. After installation, set the PATH environment variable.

3.2 Install IDE

IntelliJ IDEA is recommended due to its good integration with Spring Boot. Add the required plugins after installation.

3.3 Install Maven or Gradle

Choose one to install. If using Maven, manage dependencies through pom.xml. If using Gradle, use the build.gradle file.

4. Creating a Spring Boot Project

There are various ways to create a Spring Boot project. Here, we will introduce a method using Spring Initializr.

  1. Visit the Spring Initializr website.
  2. Enter Project Metadata:
    • Group: com.example
    • Artifact: demo
    • Dependencies: Optionally add Spring Web, Spring Data JPA, H2 Database, etc.
  3. Click the Generate button to download the ZIP file.
  4. Extract the downloaded ZIP file and open the project in your IDE.

5. Creating a Simple RESTful API

Now, let’s create a simple RESTful API using Spring Boot. The following example is a user management API.

5.1 Add Dependency

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-web</artifactId>
</dependency>

5.2 Create Model Class

package com.example.demo.model;

public class User {
    private Long id;
    private String name;
    
    // Constructor, Getter, and Setter methods
}

5.3 Create Controller Class

package com.example.demo.controller;

import org.springframework.web.bind.annotation.*;
import com.example.demo.model.User;

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

@RestController
@RequestMapping("/api/users")
public class UserController {
    private List users = new ArrayList<>();

    @GetMapping
    public List getUsers() {
        return users;
    }

    @PostMapping
    public User createUser(@RequestBody User user) {
        users.add(user);
        return user;
    }
}

5.4 Run the Application

Now when you run the application, you can check the user list at http://localhost:8080/api/users.

6. Integrating with a Database

Spring Boot can integrate with various databases. You can use several databases like H2, MySQL, PostgreSQL, etc. Here, we will use H2.

6.1 Add H2 Database Dependency

<dependency>
    <groupId>com.h2database</groupId>
    <artifactId>h2</artifactId>
    <scope>runtime</scope>
</dependency>

6.2 Configure application.properties

spring.datasource.url=jdbc:h2:mem:testdb
spring.datasource.driverClassName=org.h2.Driver
spring.datasource.username=sa
spring.datasource.password=
spring.h2.console.enabled=true

7. Writing API Documentation

As projects grow, writing API documentation becomes essential. You can easily write API documentation using Swagger.

7.1 Add Swagger Dependency

<dependency>
    <groupId>io.springfox</groupId>
    <artifactId>springfox-boot-starter</artifactId>
    <version>3.0.0</version>
</dependency>

7.2 Create Swagger Configuration Class

package com.example.demo.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import springfox.documentation.builders.PathSelectors;
import springfox.documentation.builders.RequestHandlerSelectors;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.swagger2.annotations.EnableSwagger2;

@Configuration
@EnableSwagger2
public class SwaggerConfig {
    @Bean
    public Docket api() {
        return new Docket(DocumentationType.SWAGGER_2)
                .select()
                .apis(RequestHandlerSelectors.any())
                .paths(PathSelectors.any())
                .build();
    }
}

7.3 Using Swagger UI

After running the application, you can check the API documentation through Swagger UI at http://localhost:8080/swagger-ui/.

8. Writing Test Cases

Below is an example of writing test cases using Spring Boot. We will use JUnit and Spring Test to do this.

8.1 Add Dependency

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-test</artifactId>
    <scope>test</scope>
</dependency>

8.2 Create Test Class

package com.example.demo;

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

import org.junit.jupiter.api.Test;
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.test.web.servlet.MockMvc;

@SpringBootTest
@AutoConfigureMockMvc
public class UserControllerTests {
    @Autowired
    private MockMvc mockMvc;

    @Test
    public void getUsers_ShouldReturnUsers() throws Exception {
        this.mockMvc.perform(get("/api/users"))
                .andExpect(status().isOk())
                .andExpect(jsonPath("$.length()").value(0));
    }
}

9. Conclusion

In this course, we explored how to create a simple backend application using Spring Boot. Thanks to its various features and easy configuration, Spring Boot is a useful tool for quickly developing web applications. For deeper learning, please refer to the official Spring Boot documentation.

Thank you!