Spring Boot Backend Development Course, The Emergence of Spring

Introduction

The modern software development environment is rapidly changing, particularly with the explosive increase in demand for web and mobile applications. In such an environment, there is a need for efficient development frameworks, one of which is Spring. Spring is an open-source framework based on the Java platform, providing various features such as powerful Dependency Injection, AOP (Aspect Oriented Programming), enabling developers to easily create robust applications. Today, we will take a closer look at the background of Spring’s emergence and Spring Boot.

The Background of Spring’s Emergence

The Spring framework was first introduced in 2002 in the book “Expert One-on-One J2EE Design and Development” by Rod Johnson. At that time, J2EE (Java 2 Platform, Enterprise Edition) was burdensome for many developers due to its complex structure and configuration, and the Spring framework was born to address these issues.

Problems with Existing J2EE

1. **Complex Configuration**: Building J2EE applications required a lot of configuration in XML files, making maintenance difficult.

2. **High Coupling**: In J2EE, the high coupling between objects led to decreased testability and reusability.

3. **Performance Issues**: Some APIs in J2EE were inefficient in terms of performance, consuming a lot of resources.

To solve these problems, the Spring framework pursues a lightweight structure, aiming for a modular and easily maintainable design through Dependency Injection and AOP.

Characteristics of the Spring Framework

The Spring framework has several features, including:

1. Dependency Injection

One of the core concepts of Spring, Dependency Injection, simplifies the establishment of dependencies among objects, thereby reducing coupling and increasing flexibility. Developers use Spring’s container to inject objects instead of creating them directly.

2. AOP (Aspect Oriented Programming)

AOP allows for the modularization of cross-cutting concerns. For instance, common functionalities such as logging, security, and transaction management can be separated using AOP, maintaining code consistency.

3. Modularity

Spring is divided into several modules, allowing developers to selectively use only the necessary ones. For example, various modules like Spring MVC, Spring Data, and Spring Security can be utilized individually.

The Emergence of Spring Boot

What is Spring Boot?

Spring Boot is a framework introduced in 2014 that helps developers create Spring-based applications more easily. With Spring Boot, developers can build Spring applications in a short time without complex configuration. It follows the design philosophy of ‘Convention over Configuration,’ facilitating automatic setup of basic configurations.

Features of Spring Boot

1. **Auto Configuration**: Spring Boot automatically configures necessary Beans based on the selected libraries, saving time during the initial development phase.

2. **Standalone Applications**: Applications developed with Spring Boot are packaged as JAR files and can be easily executed without additional server configurations.

3. **Production Ready**: Spring Boot is designed with application operations in mind, providing ready-to-use embedded servers and basic features like health checks and monitoring.

Conclusion

Spring and Spring Boot are indispensable tools in modern application development. The philosophy of Spring, which alleviates developers’ inconveniences stemming from complex configuration and enhances reusability through a modular approach, has evolved with the times. The emergence of Spring Boot maximizes the flexibility of Spring, helping developers rapidly build better software. We recommend keeping an eye on the changes and developments in the Spring ecosystem and participating in projects utilizing Spring.

References

  • Spring Framework Reference Documentation
  • Spring Boot Reference Documentation
  • Rod Johnson, “Expert One-on-One J2EE Design and Development”
  • Baeldung: Spring Tutorials

Spring Boot Backend Development Course, Spring Boot that Makes Spring Easier

Spring Boot is a very important framework for modern web application development. It simplifies the configuration and complexity of the Spring framework, helping developers create applications more quickly and efficiently. In this course, we will explain the concepts of Spring Boot, how it works, its advantages, and how it reduces the complexities of backend development through real projects.

1. What is Spring Boot?

Spring Boot is a framework for web application development based on the Spring framework. While the Spring framework is very powerful and flexible, its complex configuration can be a challenge for beginners or teams that want rapid development. To solve this problem, Spring Boot was introduced. Spring Boot enables the creation of ‘configuration-less’ applications, supporting efficient development.

1.1. Key Features of Spring Boot

  • Auto Configuration: Automatically configures appropriate beans based on the libraries used in the application.
  • Starters: Provides predefined dependencies to easily add various functionalities, allowing developers to quickly utilize the features they may need.
  • Production Ready: Integrates heterogeneous services and offers various features for monitoring and management.
  • Embedded Server: Includes web servers like Tomcat and Jetty, allowing applications to run without separate server configuration.

2. Advantages of Spring Boot

One of the main reasons to use Spring Boot is to enhance productivity. Spring Boot offers numerous benefits to developers through several key features.

2.1. Fast Development

By using Spring Boot starters, necessary dependencies can be easily added, and auto configuration minimizes the settings required to start and run the application. This saves time during the initial stages of development.

2.2. Easy Maintenance

As the code becomes more concise and unnecessary settings are reduced, maintaining the application becomes easier. Additionally, Spring Boot is continuously updated to reflect the latest trends, making adaptation to new technology stacks easier.

2.3. Production Ready

Spring Boot provides many production features by default, offering useful tools for service monitoring, database connection, logging, error handling, and more.

3. Getting Started with Spring Boot

Now, let’s learn how to use Spring Boot through a real project. This course will cover the process of creating a simple RESTful API.

3.1. Project Setup

There are several ways to set up a Spring Boot project, but the easiest and fastest way is to use Spring Initializr. By selecting the necessary dependencies and entering basic configurations on this site, you can receive a ZIP file containing the basic structure of a Spring Boot application.

3.2. Adding Dependencies

Dependencies needed to build a REST API include ‘Spring Web’, ‘Spring Data JPA’, and ‘H2 Database’ or a driver that matches the actual database. After selecting these dependencies, download the project.

3.3. Writing the Application Class

By default, if you look for the Application class in the src/main/java directory of the generated project, you will see that the @SpringBootApplication annotation is declared. This serves as the entry point of the Spring Boot application. You can run the application through this class.

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);
    }
}

3.4. Creating a REST Controller

The next step is to create a controller that will handle the REST API. After creating a new package under the src/main/java directory, write a class that defines the endpoints of the REST API. Use the @RestController annotation to define this and add a mapping to handle GET requests using the @GetMapping annotation.

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!";
    }
}

3.5. Running the Application

Now, when you run the application in the IDE, the embedded Tomcat server will start, and you can access http://localhost:8080/hello to see the message “Hello, Spring Boot!”.

4. Advanced Features of Spring Boot

Spring Boot provides a variety of powerful features beyond those for creating basic REST APIs, enabling the creation of scalable applications.

4.1. Database Integration

Using Spring Data JPA, you can connect to the database in an object-oriented programming way. Spring Boot automatically handles JPA-related configurations, keeping the code simple. We will cover how to connect databases and models through a board application example.

4.1.1. Creating an Entity Class

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

@Entity
public class Post {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;

    private String title;
    private String content;

    // getters and setters
}

4.1.2. Defining a Repository Interface

To utilize the features of Spring Data JPA, define an interface that extends JpaRepository to easily perform data operations.

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

public interface PostRepository extends JpaRepository {
}

4.2. Adding Security Features

By integrating Spring Security, you can add security to the application. Spring Boot offers various features that simplify security settings.

4.3. Adhering to RESTful API Design Principles

In a RESTful API, it is important to design based on resources. Using HTTP methods (GET, POST, PUT, DELETE) and status codes can clarify the interaction between client and server.

5. Real-World Project Utilizing Spring Boot

Now, let’s create a simple board application based on the main concepts and technologies of Spring Boot. This project will use various features to help you understand the overall flow of Spring Boot.

5.1. Analyzing Project Requirements

The basic requirements for the board application are as follows.

  • View list of posts
  • Create a post
  • Edit a post
  • Delete a post
  • View details of a post

5.2. Designing Models and Repositories

We will handle database operations using the previously created Post entity and PostRepository.

5.3. Adding a Service Layer

Add a service layer to handle business logic, separating responsibilities from the controller. This helps make maintenance and testing easier.

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.List;

@Service
public class PostService {
    @Autowired
    private PostRepository postRepository;

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

    public Post save(Post post) {
        return postRepository.save(post);
    }

    // CRUD operations
}

5.4. Implementing the REST API

The controller handles HTTP requests by calling the methods defined in the service layer and returns appropriate responses to the client.

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/posts")
public class PostController {
    @Autowired
    private PostService postService;

    @GetMapping
    public List getAllPosts() {
        return postService.findAll();
    }

    @PostMapping
    public ResponseEntity createPost(@RequestBody Post post) {
        Post createdPost = postService.save(post);
        return ResponseEntity.ok(createdPost);
    }

    // Additional CRUD endpoints
}

5.5. Using ControllerAdvice for Exception Handling

With Spring Boot, you can define a ControllerAdvice that globally manages exception handling and responses. This enhances the stability of the application.

import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;

@ControllerAdvice
public class GlobalExceptionHandler {
    @ExceptionHandler(Exception.class)
    public ResponseEntity handleException(Exception e) {
        return new ResponseEntity<>(e.getMessage(), HttpStatus.INTERNAL_SERVER_ERROR);
    }
}

6. Conclusion

Through this course, we explored the basic concepts and practical use cases of Spring Boot. Spring Boot reduces complex configurations and enables rapid development, supporting various production-ready features. This allows developers to focus on business logic, leading to the creation of higher-quality products. We hope you will design and implement various solutions using Spring Boot!

7. References

Spring Boot Backend Development Course, Studying Spring Concepts

Definition and Overview

Spring Boot is a framework based on Java (Spring Framework) that enables rapid development of web applications and microservices.
Spring Boot helps developers quickly create applications without complex configurations and provides various features for easily building REST APIs. In this article, we will delve into the fundamental concepts of Spring Boot and explore Spring concepts in depth.

Basic Concepts of the Spring Framework

The Spring Framework is an open-source application framework for the Java platform.
This framework consists of the following core concepts:

  • Dependency Injection: A method of managing relationships between objects without directly handling dependencies, allowing Spring to manage and create objects instead.
  • Separation of Concerns: Separating business logic from presentation logic to enhance code reusability and ease of maintenance.
  • AOP (Aspect-Oriented Programming): A method of modularizing common functionalities. It is used for log processing, transaction management, etc.

Advantages of Spring Boot

Spring Boot offers the following advantages:

  • Rapid Development: Simple configuration allows developers to implement necessary features immediately.
  • Auto Configuration: When developers add the appropriate libraries, Spring configures them automatically.
  • Standalone: Can be packaged as a JAR file, allowing it to run without a separate server.

Setting Up a Spring Boot Project

To start a Spring Boot project, you can use Spring Initializer. This tool helps you easily set up the basic structure of the project and its required dependencies.

  • First, visit Spring Initializer.
  • Enter project metadata.
  • Add the necessary dependencies and click the ‘Generate’ button to download a ZIP file.
  • Unzip the downloaded file and open it in an IDE to start development.

Basic Structure of Spring Boot

The basic structure of a Spring Boot project is divided as follows:

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

Main Annotations of Spring Boot

Spring Boot provides various annotations to help developers configure quickly. The main annotations include:

  • @SpringBootApplication: The entry point of the Spring Boot application, enabling auto-configuration and component scanning.
  • @RestController: Defines the controller for RESTful web services, returning JSON data.
  • @RequestMapping: Defines methods that handle HTTP requests.

Developing a REST API

Let’s explore how to develop a REST API using Spring Boot. A REST API communicates via the HTTP protocol and is responsible for data exchange between the client and the server. Here is a simple example of an API:

1. Writing the 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!";
        }
    }
    

2. Running and Testing

After writing the above code, when you run the application, you can send a GET request to the /hello endpoint to receive the message ‘Hello, Spring Boot!’.

Deepening Spring Concepts

We will take a deeper look at fundamental concepts of Spring Boot such as dependency injection, application context, and AOP.

Dependency Injection

Dependency injection is a core element of the Spring Framework. It allows for lower coupling and increased flexibility by injecting necessary objects from external sources rather than creating them directly.
Here is an example of dependency injection:


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

    @Service
    public class UserService {
        private final UserRepository userRepository;

        @Autowired
        public UserService(UserRepository userRepository) {
            this.userRepository = userRepository;
        }

        public User findUser(Long id) {
            return userRepository.findById(id).orElse(null);
        }
    }
    

Spring AOP

AOP is a method of modularizing common concerns in a program. It is particularly useful for logging, security, and transaction management.
With AOP, you can perform additional actions before and after specific method executions.


    import org.aspectj.lang.annotation.Aspect;
    import org.aspectj.lang.annotation.Before;
    import org.springframework.stereotype.Component;

    @Aspect
    @Component
    public class LoggingAspect {

        @Before("execution(* com.example.demo.service.*.*(..))")
        public void logBefore() {
            System.out.println("Before method call: Logging output");
        }
    }
    

Connecting to a Database

Connecting to a database using Spring Boot is also an important aspect.
You can interact easily with the database through JPA and Spring Data JPA.

1. Adding Dependencies


    dependencies {
        implementation 'org.springframework.boot:spring-boot-starter-data-jpa'
        runtimeOnly 'com.h2database:h2'
    }
    

2. Defining the Entity Class


    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
    }
    

Conclusion

Spring Boot is a framework that supports fast and easy development of Java-based applications.
In this article, we explored the basic concepts of Spring Boot, REST API development, Spring Data JPA, AOP, and more.
Utilize Spring Boot to build an efficient backend development environment.

Spring Boot Backend Development Course, Spring and Spring Boot

Introduction

With the development of modern web applications, the importance of backend development is growing day by day.
The Java-based Spring framework is one of the widely used backend technologies among many developers.
In particular, Spring Boot is emerging as a tool that enables efficient development.
In this course, we will take an in-depth look at the basic concepts of the Spring framework and the characteristics and advantages of Spring Boot.

Overview of the Spring Framework

The Spring framework is an application framework for the Java platform that provides various features to conveniently assist in enterprise-level application development.
Spring is mainly composed of the following modules.

  • Spring Core: Provides the basic features of Spring, including IoC (Inversion of Control) and DI (Dependency Injection) capabilities.
  • Spring MVC: Supports the MVC architecture for web application development.
  • Spring Data: Supports integration with various databases.
  • Spring Security: Provides robust authentication and authorization features for application security.

Differences Between Spring and Spring Boot

The Spring framework has traditionally provided flexibility in application composition and management.
However, this has resulted in the need for complex configurations and initialization processes.
On the other hand, Spring Boot is a tool developed to solve these issues.
Here are the main differences between the two frameworks.

  1. Configuration Method: Spring Boot follows the principle of ‘convention over configuration,’ allowing applications to start with minimal configuration.
  2. Embedded Server: Spring Boot supports embedded web servers such as Tomcat and Jetty, allowing applications to run without separately configuring a server.
  3. Starter Dependencies: Spring Boot provides a module called ‘starter’ to easily manage various dependencies, enabling developers to easily add required features.
  4. Actuator: Spring Boot includes an actuator module that provides various features for monitoring and managing the application’s status.

Installing and Setting Up Spring Boot

To start backend development using Spring Boot, you first need to set up your development environment.
Let’s follow the steps below to install Spring Boot and create a simple project.

1. Preparing the Development Environment

The tools required to use Spring Boot are as follows.

  • Java Development Kit (JDK): Java 8 or higher is required.
  • IDE: Choose an integrated development environment (IDE) such as IntelliJ IDEA or Eclipse that supports Java development.
  • Maven/Gradle: Choose Maven or Gradle for dependency management.

2. Creating a Spring Boot Project

Spring Boot projects can be created in various ways, but the simplest way is to use Spring Initializr.
By visiting the website and entering the required settings, you can automatically generate the initial project structure.

  • Spring Initializr Website
  • Enter Project Meta Information: Set Group, Artifact, Name, Description, Package name, etc.
  • Add Required Dependencies: Choose and add Spring Web, Spring Data JPA, H2 Database, etc.
  • Download the generated project and open it in your IDE.

Structure of a Spring Boot Application

The created Spring Boot project has the following structure.

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

Creating Your First Web Application

Let’s create a simple RESTful web service.
First, we will create a controller to handle HTTP requests.

1. Creating the HelloController Class

HelloController class is the most basic class for handling web requests and can be written 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 hello() {
                return "Hello, Spring Boot!";
            }
        }
    

2. Running the Application

Running the DemoApplication class in the IDE will start the embedded server,
and when you access http://localhost:8080/hello,
you can see the message “Hello, Spring Boot!”.

Database Integration

Spring Boot supports integration with various databases.
In this section, we will build a simple CRUD application using H2 Database.

1. Adding Dependencies

Add the H2 database and JPA-related dependencies to the pom.xml file.

        
            
            
                org.springframework.boot
                spring-boot-starter-data-jpa
            
            
            
                com.h2database
                h2
                runtime
            
        
    

2. Database Configuration

Add simple configuration in the 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=
    

3. Creating the Entity Class

Let’s create an entity class to store data in the database.
We will create a User class to store user information.

        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.AUTO)
            private Long id;
            private String name;
            private String email;

            // Getters and Setters
        }
    

4. Creating the Repository Interface

Create a repository interface to interact with the database.

        package com.example.demo.repository;

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

        public interface UserRepository extends JpaRepository {
        }
    

5. Updating the Controller

To add API endpoints that handle CRUD operations,
create a UserController and add request mappings.

        package com.example.demo.controller;

        import com.example.demo.entity.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("/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);
            }
        }
    

6. Running and Testing the Application

Restart the application, and use tools like Postman to test the
GET /users and POST /users endpoints.

Security Configuration with Spring Security

Security is very important for backend applications.
Let’s add access control and authentication through Spring Security.

1. Adding Dependencies

Add Spring Security dependency to the pom.xml file.

        
            org.springframework.boot
            spring-boot-starter-security
        
    

2. Creating the Security Configuration Class

Create a configuration class to use Spring Security.

        package com.example.demo.config;

        import org.springframework.context.annotation.Bean;
        import org.springframework.context.annotation.Configuration;
        import org.springframework.security.config.annotation.web.builders.HttpSecurity;
        import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
        import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;

        @Configuration
        @EnableWebSecurity
        public class SecurityConfig extends WebSecurityConfigurerAdapter {
            @Override
            protected void configure(HttpSecurity http) throws Exception {
                http
                    .authorizeRequests()
                    .anyRequest().authenticated()
                    .and()
                    .httpBasic();
            }
        }
    

3. Testing and Verification

Restart the application, and you can connect to API tests using HTTP Basic authentication.

Conclusion

In this course, we covered the basics of the Spring framework and the development process of
backend applications using Spring Boot.
As Spring Boot’s accessibility increases, more developers can
easily develop backend applications.
We encourage you to integrate various tools or add additional features
to create more robust applications in the future.

References

Spring Boot Backend Development Course, Implement Login and Logout with Spring Security, Membership Registration, Creating Member Domain

Hello! In this course, we will learn about backend development using Spring Boot, with a particular focus on implementing login, logout, and signup using Spring Security. This course is aimed at beginners and will cover real application development cases through practical exercises and examples. The course content generally includes the following:

  • Introduction to Spring Boot
  • Overview of Spring Security
  • Creating a member domain
  • Implementing signup functionality
  • Implementing login and logout
  • Using JWT tokens
  • Testing and conclusion

1. Introduction to Spring Boot

Spring Boot is a lightweight application framework based on the Spring Framework that helps develop applications quickly and easily. Using Spring Boot allows for simple configuration without complex XML settings, significantly contributing to productivity.

2. Overview of Spring Security

Spring Security is a framework that provides security features for Spring-based applications. It offers various functions necessary for handling authentication and authorization, helping to enhance the security of web applications.

3. Creating a member domain

To create a member domain, we first need to define the necessary entities. In this course, we will create a Member domain and set the required fields. Below is an example code of the member entity:

 
import javax.persistence.*;

@Entity
@Table(name = "members")
public class Member {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;
    
    @Column(nullable = false, unique = true)
    private String username;

    @Column(nullable = false)
    private String password;

    @Column(nullable = false)
    private String email;

    // Getters and Setters
}

4. Implementing signup functionality

Now, let’s implement the signup functionality. We will create a REST API to handle signup requests, allowing clients to send member information to the server. Below is the controller code for handling signup:


import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

@RestController
@RequestMapping("/api/members")
public class MemberController {

    @Autowired
    private MemberService memberService;

    @PostMapping("/register")
    public ResponseEntity register(@RequestBody Member member) {
        memberService.register(member);
        return new ResponseEntity<>("Signup successful", HttpStatus.CREATED);
    }
}

5. Implementing login and logout

We will use Spring Security to implement the login functionality. This will allow us to handle authentication and maintain the logged-in state of users. We will add a configuration class for Spring Security:


import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;

@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    @Autowired
    private CustomUserDetailsService customUserDetailsService;

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.userDetailsService(customUserDetailsService).passwordEncoder(passwordEncoder());
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http
            .csrf().disable()
            .authorizeRequests()
            .antMatchers("/api/members/register").permitAll()
            .anyRequest().authenticated()
            .and()
            .formLogin()
            .loginPage("/login")
            .permitAll()
            .and()
            .logout()
            .permitAll();
    }

    // PasswordEncoder bean configuration
}

6. Using JWT tokens

JWT (JSON Web Token) is a token used for exchanging secure information. We will generate JWT during signup and login to authenticate users. We will add code to issue JWT in this process:


import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;

import java.util.Date;

public class JwtUtil {

    private final String SECRET_KEY = "secret";

    public String generateToken(String username) {
        return Jwts.builder()
                .setSubject(username)
                .setIssuedAt(new Date(System.currentTimeMillis()))
                .setExpiration(new Date(System.currentTimeMillis() + 1000 * 60 * 60 * 10)) // Valid for 10 hours
                .signWith(SignatureAlgorithm.HS256, SECRET_KEY)
                .compact();
    }
}

7. Testing and conclusion

Now that all functionalities have been implemented, we will write unit tests to verify that everything works correctly. It is important to check that each feature operates as expected through testing. Below is a simple example of a unit test:


import static org.junit.jupiter.api.Assertions.*;
import org.junit.jupiter.api.Test;

public class MemberServiceTest {

    @Test
    public void testRegister() {
        Member member = new Member("testuser", "password", "test@example.com");
        memberService.register(member);
        assertNotNull(memberService.findMemberByUsername("testuser"));
    }
}

Conclusion

In this course, we explored backend development methods using Spring Boot and how to implement login, logout, and signup functionalities using Spring Security. I hope this practical experience has been helpful for you. Now, you can implement stronger user management and security features in your application.

Reference Materials