스프링 부트 백엔드 개발 강좌, OAuth2로 로그인 로그아웃 구현, OAuth2 실행 테스트하기

오늘날 웹 애플리케이션에서 인증과 권한 부여는 매우 중요한 요소이며, OAuth2는 이를 구현하는 데 널리 사용되는 표준입니다. 본 강좌에서는 스프링 부트를 사용하여 OAuth2 기반의 로그인 및 로그아웃 기능을 구현하는 방법에 대해 자세히 알아보겠습니다. 이 강좌의 목표는 스프링 부트 애플리케이션에서 OAuth2를 통해 안전한 인증 방식을 적용하고, 이를 테스트하는 방법을 배우는 것입니다.

1. OAuth2란?

OAuth2(오AUTH 2.0)는 인터넷 사용자들이 제3자 애플리케이션에 자신의 정보를 노출하지 않고도 다른 서비스에서 자신의 계정을 사용할 수 있도록 허용하는 권한 부여 프레임워크입니다. 기본적으로 OAuth2는 엑세스 토큰을 기반으로 작업하며, 이 토큰을 통해 사용자는 자신의 데이터에 접근할 수 있습니다. 이 과정에서 사용자의 비밀번호를 공유할 필요가 없습니다.

1.1 OAuth2의 구성 요소

  • Resource Owner: 자원 소유자, 일반적으로 사용자입니다.
  • Client: 자원 소유자가 서비스를 요청하는 애플리케이션입니다.
  • Authorization Server: 클라이언트의 요청을 인증하고 동의 후 엑세스 토큰을 발급하는 서버입니다.
  • Resource Server: 보호된 자원(예: 사용자 데이터)에 접근할 수 있는 서버입니다.

1.2 OAuth2 흐름

OAuth2의 인증 흐름은 다음과 같이 진행됩니다:

  1. 사용자가 클라이언트를 통해 Authorization Server에 인증 요청을 보냅니다.
  2. 사용자가 인증을 성공적으로 수행하면 Authorization Server는 클라이언트에 엑세스 토큰을 발급합니다.
  3. 클라이언트는 발급받은 엑세스 토큰을 Resource Server에 전송하여 보호된 자원에 접근합니다.

2. 스프링 부트 환경 설정

스프링 부트 환경을 설정하기 위해서는 먼저 필요한 의존성을 추가해야 합니다. 이를 위해 먼저 Spring Initializr를 활용하여 프로젝트를 생성합니다.

2.1 Spring Initializr에서 프로젝트 생성하기

다음과 같은 설정으로 스프링 부트 프로젝트를 생성합니다:

  • Project: Maven Project
  • Language: Java
  • Spring Boot: 2.6.3 (최신 버전을 선택합니다)
  • Dependencies: Spring Web, Spring Security, Spring Data JPA, H2 Database

2.2 pom.xml 파일 수정하기

다음으로, pom.xml 파일에 OAuth2 관련 의존성을 추가합니다:

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-oauth2-client</artifactId>
    </dependency>
    <dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-oauth2-resource-server</artifactId>
    </dependency>
    

3. OAuth2 설정

OAuth2을 설정하기 위해 application.yml 파일을 수정하여 Authorization Server와 Resource Server 정보를 입력합니다.

spring:
  security:
    oauth2:
      client:
        registration:
          google:
            client-id: YOUR_CLIENT_ID
            client-secret: YOUR_CLIENT_SECRET
            scope:
              - profile
              - email
            redirect-uri: "{baseUrl}/login/oauth2/code/{registrationId}"
        provider:
          google:
            authorization-uri: https://accounts.google.com/o/oauth2/auth
            token-uri: https://oauth2.googleapis.com/token
            user-info-uri: https://www.googleapis.com/oauth2/v3/userinfo
            user-name-attribute: sub
  

4. 스프링 시큐리티 설정

스프링 시큐리티를 설정하여 인증과 인가를 처리합니다. 다음은 기본적인 시큐리티 설정 클래스 예제입니다:

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()
                .antMatchers("/", "/login").permitAll()
                .anyRequest().authenticated()
                .and()
            .oauth2Login();
    }
}

5. 사용자 정보 가져오기

사용자가 인증에 성공하면, OAuth2 클라이언트를 통해 사용자 정보를 가져옵니다. 이를 위해 컨트롤러를 만듭니다.

import org.springframework.security.core.annotation.AuthenticationPrincipal;
import org.springframework.security.oauth2.core.user.OAuth2User;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class UserController {
    @GetMapping("/user")
    public OAuth2User getUser(@AuthenticationPrincipal OAuth2User principal) {
        return principal;
    }
}

6. 테스트 및 실행

애플리케이션을 실행하고 웹 브라우저에서 http://localhost:8080에 접근합니다. 사용자는 로그인 버튼을 클릭하여 Google 로그인 페이지로 리디렉션됩니다. 로그인 후, /user 경로를 통해 자신의 사용자 정보를 확인할 수 있습니다.

결론

이번 강좌에서는 스프링 부트를 사용하여 OAuth2를 통해 로그인 및 로그아웃 기능을 구현하는 방법을 살펴보았습니다. 이 과정에서 OAuth2의 기본 개념, 필요한 의존성 설정, 스프링 시큐리티 설정 및 사용자 정보 가져오기를 배웠습니다. 이러한 과정을 통해 여러분의 웹 애플리케이션에 보다 안전한 로그인 기능을 추가할 수 있게 되었습니다.

참고 문헌

스프링 부트 백엔드 개발 강좌, OAuth2로 로그인 로그아웃 구현, OAuth2 서비스 구현하기

오늘 강좌에서는 스프링 부트를 사용하여 OAuth2를 기반으로 한 로그인 및 로그아웃 기능을 어떻게 구현하는지에 대해 자세히 알아보겠습니다. OAuth2는 대표적인 인증 프로토콜로, 외부 서비스와의 통합을 통해 효율적이고 안전한 인증을 가능하게 합니다. 이 글을 통해 실질적인 예제와 함께 스프링 부트에서 어떻게 OAuth2 서비스를 구현할 수 있는지를 단계별로 설명하겠습니다.

1. OAuth2란 무엇인가?

OAuth2는 자원 소유자가 아닌 제3의 애플리케이션이 자원 소유자의 자원에 접근할 수 있도록 하는 프로토콜입니다. 이를 통해 사용자는 비밀번호를 공유할 필요 없이 애플리케이션에 접근할 수 있습니다. OAuth2는 두 가지 주요 역할을 가지고 있습니다:

  • 자원 소유자 (Resource Owner): 보통 사용자를 의미하며, 자신의 데이터를 제3의 서비스에 제공할 권한을 부여합니다.
  • 클라이언트 (Client): 사용자의 데이터를 요청하는 애플리케이션입니다.

1.1 OAuth2의 주요 구성 요소

  • Authorization Server: 사용자 인증 및 권한 부여를 처리하는 서버입니다.
  • Resource Server: 보호된 자원(예: API)을 제공하는 서버입니다.
  • Client Credentials: 애플리케이션을 식별하는 정보를 담고 있습니다.
  • Access Token: 자원 서버에 대한 접근 권한을 나타내는 토큰입니다.

2. 스프링 부트 환경 설정

스프링 부트를 사용하여 OAuth2를 설정하기 위해, 먼저 필요한 의존성을 추가해야 합니다. Gradle 또는 Maven을 사용할 수 있습니다. 여기서는 Maven을 기준으로 설명하겠습니다.

2.1 Maven 의존성 추가

pom.xml
<dependencies>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-web</artifactId>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-oauth2-client</artifactId>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-security</artifactId>
    </dependency>
</dependencies>

2.2 application.properties 설정

OAuth2 클라이언트가 사용할 기본 설정을 application.properties 파일에 추가합니다.

application.properties
spring.security.oauth2.client.registration.google.client-id=YOUR_CLIENT_ID
spring.security.oauth2.client.registration.google.client-secret=YOUR_CLIENT_SECRET
spring.security.oauth2.client.registration.google.redirect-uri={baseUrl}/login/oauth2/code/{registrationId}
spring.security.oauth2.client.registration.google.scope=email,profile
spring.security.oauth2.client.provider.google.authorization-uri=https://accounts.google.com/o/oauth2/auth
spring.security.oauth2.client.provider.google.token-uri=https://oauth2.googleapis.com/token
spring.security.oauth2.client.provider.google.user-info-uri=https://www.googleapis.com/oauth2/v3/userinfo
spring.security.oauth2.client.provider.google.user-name-attribute=sub

주의: 위의 YOUR_CLIENT_IDYOUR_CLIENT_SECRET는 Google Developer Console에서 생성한 OAuth 2.0 클라이언트의 자격 증명을 입력해야 합니다.

3. OAuth2 로그인/로그아웃 구현

이제 OAuth2를 적용할 수 있는 기본 설정이 완료되었습니다. 다음 단계로, 로그인 및 로그아웃 기능을 구현하겠습니다.

3.1 Security Configuration

스프링 시큐리티를 사용하여 웹 애플리케이션에 대한 보안 설정을 구성합니다. 다음 코드를 SecurityConfig.java 클래스에 추가합니다:

SecurityConfig.java
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()
                .antMatchers("/", "/login", "/css/**", "/js/**").permitAll()
                .anyRequest().authenticated()
            .and()
            .logout()
                .logoutSuccessUrl("/")
                .permitAll()
            .and()
            .oauth2Login();
    }
}

3.2 로그인 페이지 구현

로그인 페이지를 만들기 위해 login.html 파일을 생성하고 다음 내용을 추가합니다:

login.html
<!DOCTYPE html>
<html lang="ko">
<head>
    <meta charset="UTF-8">
    <title>로그인</title>
</head>
<body>
    <h1>로그인 페이지</h1>
    <a href="/oauth2/authorization/google">Google로 로그인</a>
</body>
</html>

3.3 사용자 정보 처리

로그인 후 사용자의 정보를 처리하는 방법을 알아보겠습니다. OAuth2UserService를 구현하여 사용자 정보를 가져올 수 있습니다.

CustomOAuth2UserService.java
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.oauth2.client.userinfo.OAuth2UserRequest;
import org.springframework.security.oauth2.client.userinfo.OAuth2UserService;
import org.springframework.security.oauth2.core.OAuth2AuthenticationException;
import org.springframework.security.oauth2.core.user.OAuth2User;
import org.springframework.stereotype.Service;

@Service
public class CustomOAuth2UserService implements OAuth2UserService<OAuth2UserRequest, OAuth2User> {

    @Override
    public OAuth2User loadUser(OAuth2UserRequest userRequest) throws OAuth2AuthenticationException {
        // 사용자 정보 처리
        // 예를 들어, 사용자 정보를 데이터베이스에 저장하거나 세션에 추가
    }
}

4. OAuth2 로그아웃 구현

로그아웃 기능은 스프링 시큐리티의 기본 제공 기능으로 쉽게 구현할 수 있습니다. SecurityConfig 클래스에서 로그아웃 성공 후 리다이렉션할 URL을 설정하였으므로, 로그아웃 버튼을 추가하면 됩니다.

4.1 로그아웃 버튼 추가

메인 페이지에 로그아웃 버튼을 추가하여 사용자가 로그아웃할 수 있도록 합니다. 대략적인 HTML 코드는 다음과 같습니다:

index.html
<!DOCTYPE html>
<html lang="ko">
<head>
    <meta charset="UTF-8">
    <title>홈 페이지</title>
</head>
<body>
    <h1>환영합니다!</h1>
    <a href="/logout">로그아웃</a>
</body>
</html>

5. 결론

오늘 강좌에서는 스프링 부트를 사용하여 OAuth2를 통한 로그인 및 로그아웃 기능을 구현하는 방법에 대해 알아보았습니다. OAuth2는 외부 서비스를 활용하여 사용자 인증을 보다 쉽고 안전하게 처리할 수 있는 유용한 방법입니다. 이번 강좌를 통해 스프링 부트와 OAuth2 설정 과정을 이해하고, 실질적인 구현 방법을 익혔기를 바랍니다.

5.1 추가 리소스

더욱 깊이 있는 내용을 원하신다면 아래의 리소스를 참고하시기 바랍니다:

스프링 부트 백엔드 개발 강좌, OAuth2로 로그인 로그아웃 구현, OAuth2 설정 파일 작성하기

1. 서론

최근 마이크로서비스 아키텍처와 클라우드 서비스를 기반으로 한 웹 애플리케이션 개발이 증가함에 따라, 스프링 부트(Spring Boot)와 같은 프레임워크의 인기도 높아지고 있습니다.
스프링 부트는 복잡한 설정 없이도 애플리케이션을 신속하게 개발할 수 있도록 도와주는 프레임워크입니다.
이번 강좌에서는 스프링 부트를 이용한 백엔드 개발에서 OAuth2를 사용하여 로그인 및 로그아웃 기능을 구현하는 방법을 자세히 알아보겠습니다.

2. OAuth2란?

OAuth2는 사용자가 클라이언트 애플리케이션에 대한 접근 권한을 제어할 수 있도록 해주는 인증 프로토콜입니다.
OAuth2를 사용하면 사용자가 자신의 자격 증명을 애플리케이션과 공유하지 않고도 특정 자원에 대한 인증 및 인가를 수행할 수 있습니다.
이는 보안을 강화하고 사용자 경험을 크게 개선할 수 있는 방법입니다.

2.1 OAuth2의 주요 구성 요소

  • Resource Owner: 클라이언트 애플리케이션에 권한을 부여하는 사용자
  • Client: Resource Owner의 자원에 접근하려는 애플리케이션
  • Resource Server: 사용자의 자원이 저장된 서버
  • Authorization Server: 사용자의 인증 정보를 처리하고 클라이언트에게 토큰을 발급하는 서버

3. 스프링 부트 프로젝트 설정

스프링 부트 애플리케이션을 시작하기 위해 먼저 새로운 프로젝트를 생성합니다.
Spring Initializr를 사용하여 Maven 또는 Gradle 기반의 프로젝트를 생성할 수 있습니다.

3.1 의존성 추가

OAuth2 인증을 구현하기 위해, 다음 의존성을 추가해야 합니다:

dependencies {
    implementation 'org.springframework.boot:spring-boot-starter-web'
    implementation 'org.springframework.boot:spring-boot-starter-security'
    implementation 'org.springframework.security.oauth.boot:spring-security-oauth2-autoconfigure:2.1.0.RELEASE'
}

3.2 application.properties 설정

다음으로, src/main/resources/application.properties 파일을 열어 OAuth2 인증에 필요한 설정을 추가합니다.
아래의 설정 예시를 참조하세요.


spring.security.oauth2.client.registration.google.client-id={YOUR_CLIENT_ID}
spring.security.oauth2.client.registration.google.client-secret={YOUR_CLIENT_SECRET}
spring.security.oauth2.client.registration.google.scope=profile, email
spring.security.oauth2.client.registration.google.redirect-uri=http://localhost:8080/login/oauth2/code/google
spring.security.oauth2.client.provider.google.authorization-uri=https://accounts.google.com/o/oauth2/auth
spring.security.oauth2.client.provider.google.token-uri=https://oauth2.googleapis.com/token
spring.security.oauth2.client.provider.google.user-info-uri=https://www.googleapis.com/oauth2/v3/userinfo

4. OAuth2 로그인 구현

이제 애플리케이션에서 OAuth2 로그인을 구현해 보겠습니다. 스프링 시큐리티(Spring Security)를 통해 간단하게 설정할 수 있습니다.

4.1 Security Configuration

새로운 Java 클래스를 생성하여 보안 설정을 구성합니다.

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()
                .antMatchers("/", "/login**", "/error**").permitAll()
                .anyRequest().authenticated()
                .and()
            .oauth2Login();
    }
}

5. 사용자 프로필 조회

사용자가 로그인하면 OAuth2 서버로부터 사용자 정보를 요청하여 프로필을 받아올 수 있습니다.
이를 위한 컨트롤러를 작성합니다.

import org.springframework.security.core.annotation.AuthenticationPrincipal;
import org.springframework.security.oauth2.core.user.OAuth2User;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;

@Controller
public class UserProfileController {
    @GetMapping("/user")
    public String user(@AuthenticationPrincipal OAuth2User principal, Model model) {
        model.addAttribute("name", principal.getAttribute("name"));
        model.addAttribute("email", principal.getAttribute("email"));
        return "userProfile";
    }
}

6. 로그아웃 구현

로그아웃 기능은 스프링 시큐리티에서 기본적으로 제공되며, 설정을 통해 손쉽게 구현할 수 있습니다.
아래와 같이 로그아웃 URL과 관련된 설정을 추가합니다.

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http
            .authorizeRequests()
                .antMatchers("/", "/login**", "/error**").permitAll()
                .anyRequest().authenticated()
                .and()
            .oauth2Login()
                .and()
            .logout()
                .logoutSuccessUrl("/")
                .invalidateHttpSession(true)
                .deleteCookies("JSESSIONID");
    }

7. 결론

본 강좌에서는 스프링 부트를 이용하여 OAuth2를 통해 로그인 및 로그아웃 기능을 구현하는 간단한 방법을 살펴보았습니다.
스프링 부트와 OAuth2를 사용하면 외부 인증 시스템과 쉽게 연동할 수 있으며, 이는 애플리케이션의 보안을 강화하고 사용자 경험을 개선하는 데에 크게 기여합니다.
앞으로 자신의 프로젝트에 OAuth2를 적용하여 보다 안전하고 편리한 서비스를 제공해 보세요!

8. 추가 자료

더 많은 정보를 원하시면 공식 문서와 기타 자료를 참조하시기 바랍니다.

스프링 부트 백엔드 개발 강좌, main 디렉터리 구성하기

스프링 부트(SPRING BOOT)는 자바 기반의 프레임워크로, 개발자가 복잡한 설정 없이도 쉽게 응용 프로그램을 구축할 수 있도록 돕는 도구입니다. 이 강좌에서는 스프링 부트 프로젝트의 main 디렉터리를 어떻게 구성할 것인지에 대한 내용을 다룰 것입니다. 이 디렉터리는 자바 애플리케이션의 시작점이자 중요한 비즈니스 로직을 구현하는 곳입니다.

스프링 부트 프로젝트 구조

스프링 부트 프로젝트는 미리 정의된 구조를 따릅니다. IDE에서 스프링 부트 프로젝트를 생성하면 다음과 같은 기본 구조가 만들어집니다.

src
├── main
│   ├── java
│   │   └── com
│   │       └── example
│   │           └── demo
│   │               ├── DemoApplication.java
│   │               └── controller
│   │               └── service
│   │               └── repository
│   └── resources
│       ├── application.properties
│       └── static
│       └── templates
└── test
    └── java

1. src/main/java 디렉터리

src/main/java 디렉터리는 실제 자바 소스 코드가 위치하는 장소로, 각 패키지와 클래스 파일이 이곳에 보관됩니다. 스프링 부트에서는 일반적으로 com.example.demo와 같은 형식으로 패키지를 구성합니다.

1.1 주 애플리케이션 클래스

DemoApplication.java 파일은 스프링 부트 애플리케이션의 시작점입니다. 이 클래스는 @SpringBootApplication 애너테이션이 부여되며, 이 애너테이션은 다음과 같은 3가지 기능을 포함합니다:

  • @Configuration: 자바 기반의 구성 클래스입니다.
  • @EnableAutoConfiguration: 스프링 부트의 자동 설정 기능을 활성화합니다.
  • @ComponentScan: 지정한 패키지를 탐색하여 스프링 컴포넌트를 자동으로 검색합니다.

아래는 주 애플리케이션 클래스의 예시입니다.

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

1.2 패키지 구조

소스 파일이 많은 경우, 적절한 패키지 구조를 정의하는 것이 중요합니다. 일반적으로 controller, service, repository와 같은 패키지를 정의합니다.

Controller 패키지

controller 패키지는 요청을 처리하고 응답을 반환하는 메소드를 포함합니다. RESTful API에서는 주로 @RestController 어노테이션을 사용하여 REST API 서버를 구성합니다.

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

Service 패키지

service 패키지는 비즈니스 로직을 처리하는 클래스를 포함합니다. 이곳의 클래스는 @Service 애너테이션을 사용하여 스프링 컨텍스트에 등록됩니다.

package com.example.demo.service;

import org.springframework.stereotype.Service;

@Service
public class HelloService {
    public String getGreeting() {
        return "Hello from Service!";
    }
}

Repository 패키지

repository 패키지는 데이터베이스와의 상호작용을 맡습니다. 보통 JpaRepository를 상속받아 CRUD 기능을 제공합니다.

package com.example.demo.repository;

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

@Repository
public interface UserRepository extends JpaRepository {
}

2. src/main/resources 디렉터리

src/main/resources 디렉터리는 애플리케이션에서 사용하는 정적 파일, 템플릿, 설정 파일 등이 위치하는 곳입니다. 이곳의 주요 파일 및 디렉터리는 다음과 같습니다.

2.1 application.properties

설정 파일인 application.properties는 애플리케이션의 환경 설정을 담당합니다. 데이터베이스 설정, 포트 번호, 로그 레벨 등을 여기서 설정할 수 있습니다.

spring.datasource.url=jdbc:mysql://localhost:3306/demo
spring.datasource.username=root
spring.datasource.password=password
server.port=8080
logging.level.org.springframework=DEBUG

2.2 static 디렉터리

static 디렉터리는 CSS, JavaScript, 이미지 파일 등 정적 리소스를 보관하는 곳입니다. 스프링 부트는 이 디렉터리의 모든 파일을 자동으로 서빙합니다.

2.3 templates 디렉터리

templates 디렉터리는 Thymeleaf와 같은 템플릿 엔진을 사용하여 동적으로 HTML 파일을 생성하는 데 사용됩니다. 여기서는 HTML 파일을 만들고 동적인 데이터를 주입할 수 있습니다.





    Welcome


    

Welcome Message

3. src/test/java 디렉터리

src/test/java 디렉터리는 애플리케이션의 테스트 관련 소스를 포함합니다. JUnit이나 Mockito와 같은 테스트 프레임워크를 사용하여 유닛 테스트와 통합 테스트를 수행합니다.

package com.example.demo;

import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;

@SpringBootTest
public class DemoApplicationTests {
    
    @Autowired
    private HelloService helloService;

    @Test
    void contextLoads() {
        assertNotNull(helloService);
    }
}

결론

이번 강좌에서는 스프링 부트 프로젝트의 main 디렉터리의 구성 방법에 대해 자세히 알아보았습니다. 프로젝트 구조를 이해하고 올바르게 구성함으로써, 개발자는 더 효율적이고 관리 가능한 코드를 작성할 수 있습니다. 이 구조는 앞으로의 유지보수와 협업에서 큰 도움이 될 것입니다. 성공적인 스프링 부트 백엔드 개발을 기원합니다.