Spring Boot Backend Development Course, Development Environment, 0.2 Creating a Spring Boot 3 Project

0.2 Creating a Spring Boot 3 Project

1. What is Spring Boot?

Spring Boot is a framework for easily building Java-based web applications and RESTful web services. It is an enhanced version of the traditional Spring Framework, helping developers to quickly develop applications with minimal setup and without complex configuration processes.

Spring Boot offers various pre-configured libraries and starter packages, enabling rapid prototyping and simple deployment. By following the ‘Convention over Configuration’ principle, developers can focus more on business logic.

2. Setting Up the Development Environment

To use Spring Boot 3, you need the Java Development Kit (JDK) and either Maven or Gradle. JDK version 17 or higher is required, and it is recommended to use IDEs like IntelliJ IDEA or Eclipse.

2.1 Installing the JDK

  1. JDK Download: Visit the Oracle JDK download page.
  2. Select and download the JDK according to your operating system.
  3. After installation, add the environment variable. For Windows, set JAVA_HOME to the JDK installation path in System Properties -> Advanced System Settings -> Environment Variables.

2.2 Installing the IDE

IntelliJ IDEA has both free and paid versions, and the free Community Edition is sufficient. After downloading and installing, you can add Maven or Gradle as plugins.

3. Creating a Spring Boot 3 Project

Now, let’s create a Spring Boot 3 project. There are two ways to create a project: using Spring Initializr or through an IDE.

3.1 Creating a Project with Spring Initializr

  1. Access Spring Initializr.

  2. Select either Maven Project or Gradle Project for the Project type.

  3. Select Java for the Language.

  4. Choose Spring Boot version 3.0.0 or higher.

  5. Input the Project Metadata, including Group, Artifact, Name, Description, and Package Name.

  6. Select necessary libraries from Dependencies. Add libraries like Web, JPA, H2, etc.

  7. Click the Generate button to download the ZIP file, and then extract it to your desired location.

3.2 Creating a Project through the IDE

  1. Open IntelliJ IDEA and select File > New > Project.
  2. Select Spring Initializr and proceed to the next steps. Set up Group, Artifact, and Dependencies.
  3. Click Finish to create the project.

3.3 Project Structure

The basic structure of the created project is as follows:

  • src
    • main
      • java
        • com
          • example
            • demo
              • DemoApplication.java
              • controller
              • service
              • repository
      • resources
        • application.properties
        • static
        • templates
    • test
      • java

4. Creating a Hello World API

Now let’s create a simple REST API that returns “Hello World”.

4.1 Creating the Controller

Create a file named HelloController.java in the src/main/java/com/example/demo/controller directory and enter the following content:


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 hello() {
        return "Hello, World!";
    }
}
            

4.2 Running the Application

  1. Run the application by executing ./mvnw spring-boot:run from the root directory of the project or by clicking the run button in the IDE.
  2. Open a web browser and navigate to http://localhost:8080/hello to see the Hello World message.

5. Connecting to a Database

Now let’s add a simple database connection. We will create a simple CRUD application using the H2 database.

5.1 Adding H2 Database Dependency

Open the pom.xml file and add the following dependency:



    com.h2database
    h2
    runtime

            

5.2 Configuring application.properties

Add the following content to the src/main/resources/application.properties file:


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=
spring.jpa.hibernate.ddl-auto=update
            

5.3 Creating the Entity Class

Create a directory named entity under src/main/java/com/example/demo/ and create a file named User.java:


package com.example.demo.entity;

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
}
            

5.4 Creating the Repository Interface

Create a file named UserRepository.java in the src/main/java/com/example/demo/repository directory:


package com.example.demo.repository;

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

public interface UserRepository extends JpaRepository {
}
            

5.5 Creating the Service Class

Create a file named UserService.java in the src/main/java/com/example/demo/service directory:


package com.example.demo.service;

import com.example.demo.entity.User;
import com.example.demo.repository.UserRepository;
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 getAllUsers() {
        return userRepository.findAll();
    }

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

5.6 Creating UserController

Create a file named UserController.java in the src/main/java/com/example/demo/controller directory:


package com.example.demo.controller;

import com.example.demo.entity.User;
import com.example.demo.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

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

    @Autowired
    private UserService userService;

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

    @PostMapping
    public User createUser(@RequestBody User user) {
        return userService.saveUser(user);
    }
}
            

6. Running and Testing the Application

Now it’s time to run the application and test the API using Postman or cURL.

6.1 Running the Application

Run the application.

6.2 Testing the API

Use a GET request to retrieve all user information:


GET http://localhost:8080/users
            

Use a POST request to create a new user:


POST http://localhost:8080/users
Content-Type: application/json

{
    "name": "John Doe",
    "email": "john@example.com"
}
            

Conclusion

In this tutorial, we learned how to create a simple backend application using Spring Boot. Thanks to the advanced features of Spring Boot, application development has become much easier. In the next tutorial, we will cover security, testing, and deployment.