Spring Boot Backend Development Course, Building a Server with Elastic Beanstalk

Building a Server with Elastic Beanstalk

Hello! In this tutorial, we will learn in detail how to develop a backend application using Spring Boot and build a server using Elastic Beanstalk (AWS Elastic Beanstalk). This course will cover the basic concepts of backend development, the features of Spring Boot, and how to configure and deploy Elastic Beanstalk.

1. What is Spring Boot?

Spring Boot is a project based on the Spring framework that helps developers build Spring applications more easily and quickly. Here are the main features of Spring Boot:

  • Auto-configuration: Spring Boot automatically configures the settings that developers need.
  • Starter Dependencies: Provides pre-configured dependencies to easily add specific features.
  • Embedded Server: Allows independent execution through embedded web servers such as Tomcat and Jetty.
  • Production-ready: Offers useful features for production environments (monitoring, logging, etc.).

1.1 Why Use Spring Boot

Using Spring Boot speeds up application development and simplifies configuration and testing. It is particularly beneficial for teams aiming for a microservices architecture, as it enables independent service development.

2. Creating a Spring Boot Project

The easiest way to create a Spring Boot project is by using Spring Initializr. This tool automatically configures the necessary dependencies and initial settings.

2.1 Creating a Project with Spring Initializr

  1. Access Spring Initializr.
  2. Enter the project metadata:
    • Project: Maven Project
    • Language: Java
    • Spring Boot: 2.x.x (select the latest stable version)
    • Group: com.example
    • Artifact: my-spring-boot-app
    • Description: Demo project for Spring Boot
    • Package Name: com.example.myspringbootapp
    • Packaging: Jar
    • Java: 11 (or the version you are using)
  3. Add Dependencies:
    • Spring Web
    • Spring Data JPA
    • H2 Database
    • Spring Boot DevTools
  4. Click the Generate button to download the zip file.

2.2 Understanding the Project Structure

When you unzip the downloaded zip file, the following basic structure is created:

my-spring-boot-app/
├── src/
│   ├── main/
│   │   ├── java/
│   │   │   └── com/example/myspringbootapp/
│   │   │       └── MySpringBootApp.java
│   │   ├── resources/
│   │   │   ├── application.properties
│   └── test/
├── pom.xml
└── ...

3. Implementing Application Logic

3.1 Creating a Simple REST API

Now let’s create a simple REST API. First, create a controller class named GreetingController.java.

package com.example.myspringbootapp;

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

@RestController
public class GreetingController {

    @GetMapping("/greet")
    public String greet(@RequestParam(value = "name", defaultValue = "World") String name) {
        return "Hello, " + name + "!";
    }
}

Now, run the project and access http://localhost:8080/greet?name=John in your browser to see the message “Hello, John!”.

4. Configuring the Database

This time, we will implement a simple CRUD API using H2 Database.

4.1 Creating the Entity Class

package com.example.myspringbootapp;

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;

    // Getters and Setters
    public Long getId() {
        return id;
    }
    public void setId(Long id) {
        this.id = id;
    }
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
}

4.2 Creating the JPA Repository

package com.example.myspringbootapp;

import org.springframework.data.jpa.repository.JpaRepository;

public interface UserRepository extends JpaRepository {
}

4.3 Implementing the Service and Controller

Now let’s create the UserService and UserController to implement CRUD functionality.

package com.example.myspringbootapp;

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

import java.util.List;
import java.util.Optional;

@Service
public class UserService {

    @Autowired
    private UserRepository userRepository;

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

    public Optional findById(Long id) {
        return userRepository.findById(id);
    }

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

    public void delete(Long id) {
        userRepository.deleteById(id);
    }
}
package com.example.myspringbootapp;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
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.findAll();
    }

    @GetMapping("/{id}")
    public ResponseEntity getUserById(@PathVariable Long id) {
        return userService.findById(id)
                .map(ResponseEntity::ok)
                .orElse(ResponseEntity.notFound().build());
    }

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

    @DeleteMapping("/{id}")
    public ResponseEntity deleteUser(@PathVariable Long id) {
        userService.delete(id);
        return ResponseEntity.noContent().build();
    }
}

5. Running the Application

Now let’s run the application. If you run the MySpringBootApp.java class in the IDE, the embedded server will start, and you can access the API.

5.1 Testing the API with Postman

You can test the API using Postman. Try creating the following basic requests:

  • GET request: http://localhost:8080/users
  • POST request: http://localhost:8080/users (Body: JSON format)
  • DELETE request: http://localhost:8080/users/{id}

6. Introduction to AWS Elastic Beanstalk

AWS Elastic Beanstalk is a service that automates the deployment and management of applications. You can deploy your Spring Boot applications to this service.

6.1 Features of Elastic Beanstalk

  • Auto-scaling: Automatically increases or decreases instances based on traffic.
  • Environment management: Manages the operating system, platform, and resources of the server.
  • Easy deployment: Applications can be deployed with just a few lines of code.

7. Deploying the Application to Elastic Beanstalk

To deploy the application to Elastic Beanstalk, follow these steps:

7.1 Create an AWS Account and Set Up an IAM User

  1. Visit the official AWS website and create an account.
  2. Add a new user through the IAM service and grant appropriate permissions.

7.2 Create an Elastic Beanstalk Environment

  1. Log in to the AWS Management Console and select Elastic Beanstalk.
  2. Click Create environment.
  3. Select the Web server environment.
  4. Select Java in the Platform and check the version.
  5. Check Upload your code under Application code and upload the zip file.
  6. Complete the environment name, resource settings, etc.

7.3 Deploying the Application

Once all settings are complete, creating the environment will automatically deploy the application. After the deployment is complete, you can access the application using the provided URL.

8. Conclusion

In this tutorial, we explored the process of developing a simple backend application using Spring Boot and deploying it to AWS Elastic Beanstalk. Through this process, you were able to directly experience the features of Spring Boot and the usefulness of AWS. It is recommended to refer to the official documentation and related materials for a deeper understanding.

If you have any questions or would like to know more, please leave a comment. Thank you!