프로젝트 개요 및 데이터베이스 설정
본 가이드는 스프링 부트 환경에서 확장성과 유지보수를 고려한 레이어드 아키텍처를 구현하는 절차를 설명합니다. 데이터 접근 계층을 먼저 설정하고 상위로 이동하는 방식으로 진행됩니다.
1. 데이터소스 연결 정보 정의
애플리케이션의 실행을 위해 외부 리소스인 데이터베이스 정보를 설정 파일에 명시해야 합니다. 다음과 같이 포맷팅하여 입력하세요.
# 서버 포트 기본값 변경 가능
server.port=8080
# MySQL 접속 드라이버 설정
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
spring.datasource.url=jdbc:mysql://127.0.0.1:3306/core_database?serverTimezone=Asia/Seoul&useSSL=false
spring.datasource.username=dev_user
spring.datasource.password=secure_pwd
# 마이다바티스 설정: 카멜케이스 자동 매핑 활성화 권장
mybatis.configuration.map-underscore-to-camel-case=true
# 로깅 필요 시 콘솔 출력 설정 uncomment 하세요
# mybatis.configuration.log-impl=org.apache.ibatis.logging.stdout.StdOutImpl
2. 애플리케이션 메인 클래스 구성
마이다바티스 매퍼 인터페이스를 인식할 수 있도록 주석 처리된 경로 스캔을 메인 진입점에 추가합니다.
@package com.sandbox.projectcore.config;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
// 🚩 매퍼 패키지를 지정하여 스캔하도록 설정
@MapperScan("com.sandbox.projectcore.infrastructure.mapper")
public class DemoApplication {
public static void main(String[] args) {
SpringApplication.run(DemoApplication.class, args);
}
}
레이어 아키텍처 (CSMN)
단순성 (Simple), 유지보수성 (Maintainable) 을 확보하기 위해 표준 4 단계 구조를 따릅니다. 코드 작성 순서는 실제 종속성 방향과 반대로, 즉 하위에서 상위 계층으로 진행됩니다.
- Entity: 데이터 모델 객체 (테이블 컬럼과 매핑)
- Mapper: 데이터베이스 쿼리 실행 인터페이스
- Service: 비즈니스 로직 처리 영역
- Controller: 외부 요청을 수신하고 응답 반환
2.1 엔티티 클래스 생성 (Entity)
데이터베이스 테이블 칼럼을 자바 객체 속성에 대응시킵니다. underscore(언더스코어) 가 포함된 경우 camelCase(카멜 표기법) 로 변환합니다.
@package com.sandbox.projectcore.domain.model;
import lombok.Data;
@Data
public class ProductInfo {
private Integer productId;
private String productName;
private Integer stockQuantity;
private Boolean isAvailable;
}
2.2 데이터 접근 인터페이스 (Mapper)
SQL 문을 직접 명명하거나 어노테이션을 사용하여 데이터를 조회하는 역할을 담당합니다. 인터페이스로 정의하여 의존성 역전 원칙을 준수합니다.
@package com.sandbox.projectcore.infrastructure.mapper;
import com.sandbox.projectcore.domain.model.ProductInfo;
import org.apache.ibatis.annotations.Select;
import java.util.Collection;
public interface ProductInfoMapper {
@Select("SELECT * FROM product_info_table")
Collection<ProductInfo> selectAllProducts();
}
2.3 비즈니스 로직 계층 (Service)
서비스 계층은 컨트롤러와 데이터 접근 계층 사이에서 중재자 역할을 수행합니다. 복잡한 로직이 예상될 경우 인터페이스와 구현체를 분리합니다.
서비스 인터페이스 정의
@package com.sandbox.projectcore.application.service;
import com.sandbox.projectcore.domain.model.ProductInfo;
import java.util.Collection;
public interface ProductService {
Collection<ProductInfo> fetchInventoryData();
}
구현체 작성
생성자 주입 방식 (@Autowired 대신 최종 필드 사용) 이 권장되는 최신 트렌드에 맞춰 코드를 정리했습니다.
@package com.sandbox.projectcore.application.service.impl;
import com.sandbox.projectcore.domain.model.ProductInfo;
import com.sandbox.projectcore.infrastructure.mapper.ProductInfoMapper;
import com.sandbox.projectcore.application.service.ProductService;
import org.springframework.stereotype.Service;
import java.util.Collection;
import java.util.Objects;
@Service
public class ProductServiceImpl implements ProductService {
private final ProductInfoMapper productMapper;
// 🚩 생성자 주입을 통해 의존성 관리
public ProductServiceImpl(ProductInfoMapper productMapper) {
this.productMapper = Objects.requireNonNull(productMapper);
}
@Override
public Collection<ProductInfo> fetchInventoryData() {
return productMapper.selectAllProducts();
}
}
2.4 웹 요청 제어 계층 (Controller)
외부 클라이언트의 HTTP 요청을 처리하고 적절한 데이터를 JSON 형식으로 반환합니다.
@package com.sandbox.projectcore.presentation.web;
import com.sandbox.projectcore.domain.model.ProductInfo;
import com.sandbox.projectcore.application.service.ProductService;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import java.util.Collection;
@RestController
public class InventoryController {
private final ProductService inventoryService;
public InventoryController(ProductService inventoryService) {
this.inventoryService = inventoryService;
}
@GetMapping("/api/inventory/list")
public Collection<ProductInfo> getAllItems() {
return inventoryService.fetchInventoryData();
}
}
실행 및 검증
메인 애플리케이션 파일을 실행하면 서버가 기동됩니다. 브라우저에서 설정된 URL 인 http://localhost:8080/api/inventory/list에 접근하면 등록된 상품 목록 데이터가 반환되어 구현 완료 여부를 확인할 수 있습니다.