Spring Boot Backend Development Course, Understanding Spring Boot 3 Code

Hello! In this course, we will understand the code of Spring Boot 3 and learn in detail about backend development methodologies. Spring Boot is a Java-based framework that helps you build web applications quickly and easily. Through this course, we will cover a wide range of topics from the basic concepts of Spring Boot to advanced features.

1. What is Spring Boot?

Spring Boot is an extension of the Spring Framework and is a tool that makes it easier to set up and deploy traditional Spring applications. Typically, setting up a Spring application requires many configuration files and XML setups, but Spring Boot simplifies this process through Auto Configuration and Starter Dependencies.

2. Main features of Spring Boot 3

  • Auto-configuration: Spring Boot automatically configures the necessary Beans based on the classpath.
  • Starter dependencies: Provides a convenient way to manage multiple dependencies.
  • Actuator: Offers tools to monitor the state and performance of the application.
  • Testing support: Spring Boot helps write test units easily.
  • Spring WebFlux: Supports reactive programming to build asynchronous applications.

3. Setting up Spring Boot 3

To use Spring Boot, you first need to set up the development environment. In this section, we will learn how to create a Spring Boot project.

3.1. Using Spring Initializr

To start a Spring Boot project, you can use Spring Initializr. This web-based tool allows you to set up all the necessary dependencies.

https://start.spring.io

By entering the project’s metadata and adding the required dependencies at the above link, you can download the basic skeleton of a Spring Boot project.

3.2. IDE setup

Load the downloaded project into an IDE (Integrated Development Environment, e.g., IntelliJ IDEA or Eclipse). This process will automatically set up dependency management through Maven or Gradle.

4. Spring Boot application structure

A Spring Boot project has the following structure:


com.example.demo
├── DemoApplication.java
├── controller
│   ├── HelloController.java
├── service
│   ├── HelloService.java
└── repository
    ├── HelloRepository.java

Each folder serves the following roles:

  • controller: Contains controllers that handle client requests.
  • service: Contains service classes that handle business logic.
  • repository: Contains repositories that manage interactions with the database.

5. Creating a basic web application

Now, let’s create a simple web application. This application will create a REST API that returns a “Hello, World!” message.

5.1. HelloController.java

Write the controller class as follows:


package com.example.demo.controller;

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

@RestController
public class HelloController {
    @GetMapping("/hello")
    public String sayHello() {
        return "Hello, World!";
    }
}

5.2. DemoApplication.java

The main application class is as follows:


package com.example.demo;

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

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

5.3. Running the application

Now run the application and enter http://localhost:8080/hello in your web browser to see the “Hello, World!” message.

6. Dependency management in Spring Boot

Spring Boot manages dependencies through Maven or Gradle. We will use Maven by default.

6.1. Modifying pom.xml

Add the necessary dependencies to the project’s pom.xml file. Below are the basic dependencies for a RESTful service:


<project xmlns="http://maven.apache.org/POM/4.0.0"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>com.example</groupId>
    <artifactId>demo</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <packaging>jar</packaging>

    <name>demo</name>
    <description>Demo project for Spring Boot</description>

    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>3.0.0</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>

    <properties>
        <jdk.version>17</jdk.version>
    </properties>

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

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>
</project>

7. Integrating with a database

You can implement simple CRUD (Create, Read, Update, Delete) functionality using Spring Boot. In this section, we will explain how to integrate with a database using H2.

7.1. Adding H2 database dependency

The H2 database is an in-memory database suitable for testing and development. Add the following dependency to pom.xml:


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

7.2. Database configuration

Now modify the application.properties file to add the database configuration:


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

7.3. Defining the entity class

Next, create a User entity class that can store simple user information:


package com.example.demo.model;

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;

    private String email;

    // getters and setters
}

7.4. Creating the repository

Now define the UserRepository interface that provides CRUD functionality for the User entity:


package com.example.demo.repository;

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

public interface UserRepository extends JpaRepository {
}

8. Implementing the RESTful API

Finally, let’s implement the CRUD API for the User entity.

8.1. UserController.java

Write the controller that provides the RESTful API as follows:


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.http.HttpStatus;
import org.springframework.http.ResponseEntity;
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 ResponseEntity createUser(@RequestBody User user) {
        return new ResponseEntity<>(userRepository.save(user), HttpStatus.CREATED);
    }

    @GetMapping("/{id}")
    public ResponseEntity getUserById(@PathVariable(value = "id") Long userId) {
        return userRepository.findById(userId)
                .map(user -> new ResponseEntity<>(user, HttpStatus.OK))
                .orElse(new ResponseEntity<>(HttpStatus.NOT_FOUND));
    }

    @PutMapping("/{id}")
    public ResponseEntity updateUser(@PathVariable(value = "id") Long userId, @RequestBody User userDetails) {
        return userRepository.findById(userId)
                .map(user -> {
                    user.setName(userDetails.getName());
                    user.setEmail(userDetails.getEmail());
                    return new ResponseEntity<>(userRepository.save(user), HttpStatus.OK);
                })
                .orElse(new ResponseEntity<>(HttpStatus.NOT_FOUND));
    }

    @DeleteMapping("/{id}")
    public ResponseEntity deleteUser(@PathVariable(value = "id") Long userId) {
        return userRepository.findById(userId)
                .map(user -> {
                    userRepository.delete(user);
                    return new ResponseEntity(HttpStatus.NO_CONTENT);
                })
                .orElse(new ResponseEntity<>(HttpStatus.NOT_FOUND));
    }
}

9. Testing and deployment

Spring Boot allows you to perform tests using JUnit. Efficiently writing tests can enhance the quality of the application.

9.1. Writing test code

Let’s write some simple test code:


package com.example.demo;

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

import static org.mockito.Mockito.*;

public class UserControllerTest {

    @InjectMocks
    private UserController userController;

    @Mock
    private UserRepository userRepository;

    @BeforeEach
    void setUp() {
        MockitoAnnotations.openMocks(this);
    }

    @Test
    void getAllUsers() {
        userController.getAllUsers();
        verify(userRepository, times(1)).findAll();
    }

    @Test
    void createUser() {
        User user = new User();
        user.setName("Test User");
        when(userRepository.save(user)).thenReturn(user);

        userController.createUser(user);
        verify(userRepository, times(1)).save(user);
    }
}

9.2. Application deployment

Spring Boot applications can be packaged and deployed as standalone JAR files. You can build it using Maven:

mvn clean package

Then you can start the server by running the created JAR file located in the target directory:

java -jar demo-0.0.1-SNAPSHOT.jar

10. Spring Boot microservices architecture

Spring Boot is very useful for building a microservices architecture. You can build multiple independent services and configure them to communicate with each other.

10.1. Advantages of microservices

  • Independent deployment: Each service can be deployed independently.
  • Scalability: Services can be scaled according to their needs.
  • Flexibility: There is flexibility in the technology stack.

11. FAQ

11.1. What basic knowledge is required to learn Spring Boot?

A basic understanding of the Java programming language and the Spring Framework is needed.

11.2. What recommended resources are there for learning Spring Boot?

The official Spring documentation, online courses, and related books are recommended.

12. Conclusion

In this course, we explored the basic structure and features of Spring Boot 3. Spring Boot is a very powerful framework that provides the advantage of rapidly developing various applications. I hope you continue to learn deeply and acquire more features!