개발공부/Spring

[Spring] Service로 비즈니스 로직 처리하기

jnnjnn 2024. 5. 1. 20:45

 

Service란?

Controller 대신 비즈니스 로직을 처리합니다. 대규모 프로그램일수록 Controller와 Service의 분산 작업이 중요합니다.

간단한 프로그램으로 Controller, Service, Mapper의 실행 흐름만 알아보겠습니다

 

실행 흐름

1. Controller가 요청을 분석하고 가공합니다

2. Service가 비즈니스 로직을 실행합니다

3. Mapper가 데이터 CRUD를 처리하고, 결과값을 DTO에 담아 서비스에 보냅니다

4. Service가 DTO를 Controller에 전달합니다

5. Controller는 결과값을 모델에 담고 view로 포워딩 합니다

 

 

DTO(Data Transfer Object, 데이터 전송 객체)

프로세스 간에 데이터를 전달하는 객체를 의미합니다.

 

 

사용 예제

Service 역시 @Component로 스프링 빈을 생성하여 사용해야 하며, @Component 대신 @Service 어노테이션을 사용할 수 있습니다

 

월별 구매 금액을 조회하는 예제입니다

 

@Controller
@RequestMapping("main34")
@RequiredArgsConstructor
public class Controller34 {
    private final Service01 service;

    @RequestMapping("sub2")
    public void method2(Integer year, Integer month, Model model) {
        List<Mapper05.Customer> list = service.customersBuyList(year, month);

        model.addAttribute("priceList", list);
        model.addAttribute("year", year);
        model.addAttribute("month", month);
    }
}

 

Controller에 Service01 객체를 의존성 주입합니다

@Service
@RequiredArgsConstructor
public class Service01 {
    private final Mapper05 mapper05;

    public List<Mapper05.Customer> customersBuyList(Integer year, Integer month) {
        String from = "%d-%02d-01".formatted(year, month);
        String to = "%d-%02d-31".formatted(year, month);

        return mapper05.customerBuy(from, to);
    }
}

 

1) Service로 사용하기 위해 @Service 어노테이션을 붙이고 Mapper05 객체를 의존성 주입해줍니다

2) 전달받은 year와 month 데이터가 쿼리 형식에 맞도록 가공합니다

@Mapper
public interface Mapper05 {
    @Data
    static class Customer {
        private Integer CustomerID;
        private String customerName;
        private Double sumOfPrice;
    }

    @Select("""
                SELECT c.CustomerID, c.CustomerName, SUM(p.Price * od.Quantity) sumOfPrice
                FROM Customers c
                JOIN Orders o ON o.CustomerID = c.CustomerID
                JOIN OrderDetails od ON o.OrderID = od.OrderID
                JOIN Products p ON p.ProductID = od.ProductID
                WHERE o.OrderDate BETWEEN #{from} AND #{to}
                GROUP BY c.CustomerID
                ORDER BY sumOfPrice DESC
            """)
    List<Customer> customerBuy(String from, String to);
}
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@ taglib prefix="c" uri="jakarta.tags.core" %>
<html>
<head>
    <title>Title</title>
    <style>
        tr, td, th, table {
            border-collapse: collapse;
            border: 1px solid black;
        }
    </style>
</head>
<body>
<h3>월별 고객 구매금액 조회</h3>
<form action="">
    년도
    <div>
        <select name="year">
            <option value="1996" ${year == '1996' ? 'selected' : ''}>1996</option>
            <option value="1997" ${year == '1997' ? 'selected' : ''}>1997</option>
        </select>
    </div>
    <div><select name="month" id="">
            <option value="1" ${month == '1' ? 'selected' : ''}>1</option>
            <option value="2" ${month == '2' ? 'selected' : ''}>2</option>
            <option value="3" ${month == '3' ? 'selected' : ''}>3</option>
            <option value="4" ${month == '4' ? 'selected' : ''}>4</option>
            <option value="5" ${month == '5' ? 'selected' : ''}>5</option>
            <option value="6" ${month == '6' ? 'selected' : ''}>6</option>
            <option value="7" ${month == '7' ? 'selected' : ''}>7</option>
            <option value="8 ${month == '8' ? 'selected' : ''}">8</option>
            <option value="9" ${month == '9' ? 'selected' : ''}>9</option>
            <option value="10" ${month == '10' ? 'selected' : ''}>10</option>
            <option value="11" ${month == '11' ? 'selected' : ''}>11</option>
            <option value="12" ${month == '12' ? 'selected' : ''}>12</option>
        </select>
    </div>
    <input type="submit" value="조회">
</form>
<hr>
<c:if test="${empty priceList}">
    <div>
        조회 결과가 없습니다
    </div>
    <div>
        1996년 7월부터 1997년 11월 중에 조회 해주세요
    </div>
</c:if>
<c:if test="${not empty priceList}">
    <h3>
            ${param.year}년 ${param.month}월 조회 결과
    </h3>
    <table>
        <thead>
        <tr>
            <th>#</th>
            <th>고객번호</th>
            <th>고객이름</th>
            <th>구매금액</th>
        </tr>
        </thead>
        <c:forEach items="${priceList}" var="item" varStatus="status">
            <tbody>
            <tr>
                <td>${status.count}</td>
                <td>${item.customerID}</td>
                <td>${item.customerName}</td>
                <td>${item.sumOfPrice}</td>
            </tr>
            </tbody>
        </c:forEach>
    </table>
</c:if>
</body>
</html>

 

결과