본문 바로가기
개발

💡 Spring Boot 3.0 시작하기: 초보자를 위한 완벽 가이드

by D-Project 2025. 5. 25.

안녕하세요, 백엔드 개발의 세계로 첫 발을 내딛는 여러분! 🚀 오늘은 현대 자바 백엔드 개발의 핵심이라 할 수 있는 Spring Boot 3.0에 대해 알아보려고 합니다. 복잡하게 느껴질 수 있는 Spring의 세계를 쉽고 재미있게 탐험해 봅시다!

📋 목차

Spring Boot 3.0이란?

Spring Boot는 Java 기반의 웹 애플리케이션과 마이크로서비스를 빠르고 쉽게 개발할 수 있게 해주는 프레임워크입니다. 특히 Spring Boot 3.0은 2022년 11월에 출시된 메이저 업데이트로, Java 17을 기본으로 채택하고 다양한 성능 개선과 새로운 기능을 제공합니다.

Spring Boot의 핵심 철학 🧠

  • 관례적 설정(Convention over Configuration): 개발자가 일일이 모든 설정을 하지 않아도 됩니다
  • 스타터 종속성(Starter Dependencies): 주요 기능을 쉽게 추가할 수 있습니다
  • 자동 구성(Auto-configuration): 애플리케이션 요구사항에 맞게 자동으로 설정됩니다
  • 내장 서버(Embedded Server): 별도의 웹 서버 설정 없이 애플리케이션을 실행할 수 있습니다
  • 액추에이터(Actuator): 애플리케이션 모니터링과 관리 기능을 제공합니다

Spring Boot 3.0의 주요 변경사항 🆕

변경사항 설명 중요도 ⭐
Java 17 지원 최신 자바 버전의 기능을 활용할 수 있습니다 ⭐⭐⭐⭐⭐
Jakarta EE 9+ Java EE에서 Jakarta EE로의 네임스페이스 변경 ⭐⭐⭐⭐
네이티브 이미지 GraalVM을 통한 네이티브 이미지 생성 지원 강화 ⭐⭐⭐
성능 최적화 애플리케이션 시작 시간 및 메모리 사용량 개선 ⭐⭐⭐⭐
관측 가능성 Micrometer와 Zipkin을 통한 모니터링 기능 강화 ⭐⭐⭐
HTTP 인터페이스 선언적 HTTP 클라이언트 지원 ⭐⭐⭐

시작하기 전에 알아야 할 것들

Spring Boot 3.0을 배우기 전에 알아두면 좋은 기본 지식들이 있습니다:

  • Java 기초: 객체지향 프로그래밍, 제네릭, 람다 표현식, 스트림 API
  • 웹 개발 기초: HTTP, REST API, JSON
  • 데이터베이스 기초: SQL, JDBC, JPA
  • 빌드 도구: Maven 또는 Gradle
  • 버전 관리: Git

이 모든 것을 완벽하게 알 필요는 없습니다! Spring Boot의 매력은 배우면서 해보기(Learning by Doing)에 있습니다. 👍

개발 환경 설정하기

필요한 도구들 🛠️

  1. JDK 17 이상: Adoptium에서 다운로드 가능
  2. IntelliJ IDEA: Community Edition도 충분합니다
  3. Maven 또는 Gradle: 대부분의 경우 IDE에 내장되어 있습니다
  4. Postman: API 테스트를 위한 도구

Spring Initializr로 프로젝트 생성하기 🌱

Spring Initializr는 Spring Boot 프로젝트를 쉽게 만들 수 있는 웹 도구입니다.

  1. 프로젝트 메타데이터 설정
    • Project: Maven 또는 Gradle
    • Language: Java
    • Spring Boot: 3.0.x 선택
    • Group: com.example (조직 ID)
    • Artifact: demo (프로젝트 이름)
    • Packaging: Jar
    • Java: 17
  2. 종속성 추가
    • Spring Web: RESTful API 개발
    • Spring Data JPA: 데이터베이스 연동
    • H2 Database: 내장 데이터베이스
    • Spring Boot DevTools: 개발 편의성
    • Lombok: 반복 코드 감소
  3. GENERATE 클릭 후 프로젝트 다운로드

IntelliJ IDEA에서 프로젝트 열기 🖥️

  1. IntelliJ IDEA 실행
  2. "Open" 선택
  3. 다운로드받은.zip 파일 압축 해제 후 폴더 선택
  4. 프로젝트 구조 확인:
    • src/main/java: 자바 코드
    • src/main/resources: 설정 파일
    • src/test: 테스트 코드
    • pom.xml 또는 build.gradle: 빌드 설정

첫 번째 Spring Boot 애플리케이션 만들기

Hello World 애플리케이션 만들기 👋

  1. 메인 애플리케이션 클래스 확인 (자동 생성됨)
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. 첫 번째 컨트롤러 만들기
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 3.0!";
    }
}
  1. 애플리케이션 실행
    • IntelliJ에서 메인 클래스 실행
    • 또는 터미널에서 ./mvnw spring-boot:run (Maven) 또는 ./gradlew bootRun (Gradle)
  2. 브라우저에서 http://localhost:8080/hello 접속
    • "Hello, Spring Boot 3.0!" 메시지가 표시됩니다! 🎉

Spring Boot 3.0의 주요 기능

1. 강력한 의존성 주입(DI) 시스템 💉

Spring의 핵심은 의존성 주입입니다. 객체들의 의존 관계를 외부에서 설정해줍니다.

@Service
public class UserService {
    private final UserRepository userRepository;

    // 생성자 주입 방식 (권장)
    @Autowired
    public UserService(UserRepository userRepository) {
        this.userRepository = userRepository;
    }

    // 비즈니스 로직...
}

2. 애노테이션 기반 설정 🏷️

Spring Boot는 XML 대신 애노테이션을 통한 설정을 권장합니다.

애노테이션 설명 사용 위치
@RestController REST API 엔드포인트 정의 클래스
@Service 비즈니스 로직을 담당하는 클래스 클래스
@Repository 데이터 액세스 클래스 클래스
@Component 일반적인 스프링 관리 컴포넌트 클래스
@Autowired 의존성 주입 생성자, 필드, 메서드
@GetMapping HTTP GET 요청 매핑 메서드
@PostMapping HTTP POST 요청 매핑 메서드

3. 자동 설정(Auto-configuration) ⚙️

Spring Boot는 클래스패스에 있는 라이브러리와 애노테이션을 기반으로 자동으로 애플리케이션을 설정합니다.

예를 들어, spring-boot-starter-data-jpa를 추가하면 데이터베이스 연결과 JPA 설정이 자동으로 구성됩니다.

4. 프로필(Profiles) 기반 설정 📊

다양한 환경(개발, 테스트, 운영)에 맞는 설정을 프로필로 분리할 수 있습니다.

# application.yml
spring:
  profiles:
    active: dev

---
spring:
  config:
    activate:
      on-profile: dev
  datasource:
    url: jdbc:h2:mem:testdb
    username: sa
    password: 

---
spring:
  config:
    activate:
      on-profile: prod
  datasource:
    url: jdbc:mysql://production-db:3306/myapp
    username: ${DB_USERNAME}
    password: ${DB_PASSWORD}

RESTful API 개발하기

REST API 기초 📡

REST(Representational State Transfer)는 웹 서비스를 설계하는 아키텍처 스타일입니다. Spring Boot는 RESTful API를 쉽게 개발할 수 있는 도구를 제공합니다.

모델 클래스 만들기 📝

package com.example.demo.model;

import jakarta.persistence.Entity;
import jakarta.persistence.GeneratedValue;
import jakarta.persistence.Id;
import lombok.Data;

@Data
@Entity
public class Product {
    @Id
    @GeneratedValue
    private Long id;
    private String name;
    private String description;
    private double price;
}

레포지토리 인터페이스 정의 📊

package com.example.demo.repository;

import com.example.demo.model.Product;
import org.springframework.data.jpa.repository.JpaRepository;

public interface ProductRepository extends JpaRepository<Product, Long> {
    // 특별한 쿼리 메서드 정의 가능
    // 기본 CRUD 작업은 JpaRepository에서 제공됨
}

서비스 클래스 구현 ⚙️

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;
import java.util.Optional;

@Service
public class ProductService {
    private final ProductRepository productRepository;

    @Autowired
    public ProductService(ProductRepository productRepository) {
        this.productRepository = productRepository;
    }

    public List<Product> findAllProducts() {
        return productRepository.findAll();
    }

    public Optional<Product> findProductById(Long id) {
        return productRepository.findById(id);
    }

    public Product saveProduct(Product product) {
        return productRepository.save(product);
    }

    public void deleteProduct(Long id) {
        productRepository.deleteById(id);
    }
}

REST 컨트롤러 구현 🎮

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 {
    private final ProductService productService;

    @Autowired
    public ProductController(ProductService productService) {
        this.productService = productService;
    }

    @GetMapping
    public List<Product> getAllProducts() {
        return productService.findAllProducts();
    }

    @GetMapping("/{id}")
    public ResponseEntity<Product> getProductById(@PathVariable Long id) {
        return productService.findProductById(id)
                .map(ResponseEntity::ok)
                .orElse(ResponseEntity.notFound().build());
    }

    @PostMapping
    @ResponseStatus(HttpStatus.CREATED)
    public Product createProduct(@RequestBody Product product) {
        return productService.saveProduct(product);
    }

    @PutMapping("/{id}")
    public ResponseEntity<Product> updateProduct(@PathVariable Long id, @RequestBody Product product) {
        return productService.findProductById(id)
                .map(existingProduct -> {
                    product.setId(id);
                    return ResponseEntity.ok(productService.saveProduct(product));
                })
                .orElse(ResponseEntity.notFound().build());
    }

    @DeleteMapping("/{id}")
    public ResponseEntity<Void> deleteProduct(@PathVariable Long id) {
        return productService.findProductById(id)
                .map(product -> {
                    productService.deleteProduct(id);
                    return ResponseEntity.noContent().<Void>build();
                })
                .orElse(ResponseEntity.notFound().build());
    }
}

데이터베이스 연동하기

JPA 설정 🗄️

Spring Boot는 JPA(Java Persistence API)를 통해 데이터베이스와 쉽게 연동할 수 있습니다.

# application.yml
spring:
  datasource:
    url: jdbc:h2:mem:testdb
    username: sa
    password:
  h2:
    console:
      enabled: true
  jpa:
    hibernate:
      ddl-auto: update
    show-sql: true

다양한 데이터베이스 지원 🌐

Spring Boot는 다양한 데이터베이스를 지원합니다:

데이터베이스 의존성 특징
H2 spring-boot-starter-data-jpa, h2 내장 메모리 DB, 개발용
MySQL spring-boot-starter-data-jpa, mysql-connector-java 관계형 DB, 범용성
PostgreSQL spring-boot-starter-data-jpa, postgresql 고급 기능 제공
MongoDB spring-boot-starter-data-mongodb NoSQL, 문서 지향
Redis spring-boot-starter-data-redis 인메모리 캐시, 세션 관리

테스트 코드 작성하기

테스트의 중요성 ✅

Spring Boot는 테스트를 위한 강력한 도구를 제공합니다:

  • 단위 테스트: JUnit 5
  • 통합 테스트: Spring Test
  • 웹 레이어 테스트: MockMvc

JUnit 5를 활용한 단위 테스트 🧪

package com.example.demo.service;

import com.example.demo.model.Product;
import com.example.demo.repository.ProductRepository;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.mockito.Mock;
import org.mockito.MockitoAnnotations;

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

import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.Mockito.*;

class ProductServiceTest {
    @Mock
    private ProductRepository productRepository;

    private ProductService productService;

    @BeforeEach
    void setUp() {
        MockitoAnnotations.openMocks(this);
        productService = new ProductService(productRepository);
    }

    @Test
    void shouldReturnAllProducts() {
        // Given
        Product product1 = new Product();
        product1.setId(1L);
        product1.setName("Product 1");

        Product product2 = new Product();
        product2.setId(2L);
        product2.setName("Product 2");

        List<Product> products = Arrays.asList(product1, product2);
        when(productRepository.findAll()).thenReturn(products);

        // When
        List<Product> result = productService.findAllProducts();

        // Then
        assertThat(result).hasSize(2);
        assertThat(result).containsExactly(product1, product2);
        verify(productRepository, times(1)).findAll();
    }

    // 추가 테스트 케이스...
}

Spring Boot 통합 테스트 📋

package com.example.demo.controller;

import com.example.demo.model.Product;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.http.MediaType;
import org.springframework.test.web.servlet.MockMvc;

import static org.hamcrest.Matchers.hasSize;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;

@SpringBootTest
@AutoConfigureMockMvc
class ProductControllerTest {
    @Autowired
    private MockMvc mockMvc;

    @Autowired
    private ObjectMapper objectMapper;

    @Test
    void shouldCreateProduct() throws Exception {
        Product product = new Product();
        product.setName("Test Product");
        product.setDescription("This is a test product");
        product.setPrice(9.99);

        mockMvc.perform(post("/api/products")
                .contentType(MediaType.APPLICATION_JSON)
                .content(objectMapper.writeValueAsString(product)))
                .andExpect(status().isCreated())
                .andExpect(jsonPath("$.name").value("Test Product"))
                .andExpect(jsonPath("$.price").value(9.99));
    }

    @Test
    void shouldReturnAllProducts() throws Exception {
        mockMvc.perform(get("/api/products"))
                .andExpect(status().isOk())
                .andExpect(jsonPath("$", hasSize(1)));
    }

    // 추가 테스트 케이스...
}

Spring Boot 3.0 활용 사례

다양한 애플리케이션 유형 🎯

Spring Boot 3.0은 다양한 유형의 애플리케이션 개발에 활용됩니다:

  1. REST API 백엔드 서비스
    • 모바일 앱과 웹 클라이언트를 위한 백엔드
    • 마이크로서비스 아키텍처의 기반
  2. 웹 애플리케이션
    • Thymeleaf, Freemarker 등 템플릿 엔진 활용
    • 전통적인 서버 사이드 렌더링
  3. 마이크로서비스
    • Spring Cloud와 연동한 분산 시스템
    • 서비스 디스커버리, 설정 관리, 로드 밸런싱
  4. 배치 프로세싱
    • Spring Batch를 활용한 대용량 데이터 처리
    • 정기 작업, 데이터 마이그레이션
  5. 이벤트 기반 애플리케이션
    • Spring Cloud Stream, Kafka, RabbitMQ 연동
    • 실시간 데이터 처리

실제 사례 연구 📊

회사 산업 Spring Boot 활용
Netflix 스트리밍 서비스 간 통신, 마이크로서비스 아키텍처
Capital One 금융 서비스 기반 아키텍처, 온라인 뱅킹 플랫폼
Alibaba 전자상거래 고성능 웹 애플리케이션, 분산 시스템
Baidu 검색/AI 백엔드 서비스, 데이터 처리 파이프라인
배달의민족 음식 배달 주문 관리 시스템, 결제 처리

개발자 유형별 학습 로드맵

👶 백엔드 초보자 로드맵

  1. 기초 다지기 (1-2주)
    • Spring 핵심 개념 학습
    • 첫 번째 Spring Boot 애플리케이션 만들기
    • REST API 기초 이해하기
  2. 실전 연습 (3-4주)
    • CRUD 애플리케이션 개발
    • H2 데이터베이스 연동
    • 간단한 테스트 작성
  3. 확장하기 (5-8주)
    • 외부 API 연동
    • 예외 처리 개선
    • 로깅 설정
    • 실제 데이터베이스 연동 (MySQL, PostgreSQL)

👨‍💻 중급 개발자 로드맵

  1. 아키텍처 개선 (2-3주)
    • 계층형 아키텍처 이해와 구현
    • DTOs와 엔티티 분리
    • 유효성 검사 적용
  2. 보안 강화 (3-4주)
    • Spring Security 적용
    • JWT 인증 구현
    • 역할 기반 접근 제어
  3. 성능 최적화 (4-6주)
    • 캐싱 전략 수립
    • N+1 문제 해결
    • JPA 쿼리 최적화

🧙‍♂️ 시니어 개발자 로드맵

  1. 마이크로서비스 아키텍처 (4-6주)
    • Spring Cloud 도입
    • 서비스 디스커버리 구현
    • API 게이트웨이 설정
  2. 관측 가능성 향상 (3-4주)
    • Prometheus, Grafana 통합
    • Distributed Tracing 구현
    • 로그 집계 시스템 연동
  3. CI/CD 파이프라인 구축 (3-5주)
    • Docker 컨테이너화
    • Jenkins 또는 GitHub Actions 설정
    • Kubernetes 배포 자동화

마무리 및 다음 단계

Spring Boot 3.0은 현대적인 Java 백엔드 개발을 위한 완벽한 플랫폼입니다. 이 가이드를 통해 기본 개념을 이해하고 첫 번째 애플리케이션을 만드는 방법을 배웠습니다.

학습을 지속하기 위한 팁 🌱

  1. 공식 문서 참조하기: Spring Boot 공식 문서는 최고의 학습 자료입니다.
  2. 샘플 프로젝트 분석하기: Spring Boot Samples를 통해 다양한 예제를 확인하세요.
  3. 커뮤니티 참여하기: Stack Overflow, Spring 포럼에서 질문하고 배우세요.
  4. 실제 프로젝트 만들기: 개인 프로젝트를 통해 배운 내용을 적용해보세요.
  5. 깊이 있는 학습: Spring Framework 5: 초보자에서 구루로와 같은 온라인 강좌를 활용하세요.

다음 단계로 추천하는 주제 🚀

  • Spring Security: 인증과 권한 부여 구현
  • Spring Data MongoDB: NoSQL 데이터베이스 연동
  • Spring Cloud: 마이크로서비스 아키텍처 구현
  • Spring WebFlux: 반응형 프로그래밍 모델 학습
  • Spring Native: 네이티브 이미지 생성 및 최적화

이제 여러분은 Spring Boot 3.0의 기본기를 갖추게 되었습니다! 계속해서 학습하고 개발하며, 더 복잡하고 흥미로운 프로젝트에 도전해보세요. 여러분의 Spring Boot 여정이 즐겁고 성공적이기를 바랍니다! 🎉