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!