본문 바로가기
Kotlin Spring/Kotlin Spring 강의 내용

4) Spring @controller, @service, @repository

by Bill Lab 2025. 8. 29.
728x90

스프링은 기본적으로 레이어드 아키텍처(Layered Architecture)를 따르는데, 보통 다음 3단계로 나뉨

 

1. Controller(라우팅 역할)

     : “문 앞에서 손님을 맞이하는 안내원”

        1) 클라이언트(웹/앱) 요청을 받고, 어떤 서비스가 필요할지 결정

        2) 비즈니스 로직은 직접 하지 않고, Service로 위임

import org.springframework.web.bind.annotation.*

@RestController
@RequestMapping("/users")
class UserController(
    private val userService: UserService
) {
    @PostMapping
    fun createUser(@RequestBody request: CreateUserRequest): User {
        return userService.registerUser(request.name, request.email)
    }

    @GetMapping
    fun listUsers(): List<User> = userService.getAllUsers()
}

 

2. Service(비지니스 로직 처리)

     : “가게 안에서 실제 요리를 만드는 요리사”

       1) 데이터 처리를 위해 Repository를 호출

       2) 트랜잭션 처리 같은 핵심 로직 수행

import org.springframework.stereotype.Service
import org.springframework.transaction.annotation.Transactional

@Service
class PointService(
    private val userRepository: UserRepository
) {
    @Transactional
    fun addPoint(userId: Long, points: Int): User {
        val user = userRepository.findById(userId)
            .orElseThrow { IllegalArgumentException("Member not found: $userId") }
   
        if (points % 100 != 0) {
            throw IllegalArgumentException("Points must be added in multiples of 100")
        }

        user.points += points
        return user
    }
}

 

3. Repository(Data 처리)

     : “식자재를 보관하는 창고 관리자”

      1) DB와 직접 통신 (CRUD 담당)

      2) Service가 요청할 때 필요한 데이터 제공

 

import org.springframework.data.jpa.repository.JpaRepository
import org.springframework.stereotype.Repository

@Entity
data class User(
    @Id 
    val id: Long? = null,
    val name: String,
    val email: String
)

@Repository
interface UserRepository : JpaRepository<User, Long>
//스프링 JPA가 자동으로 findById, save, deleteById 등을 만들어줌

 

이번 강의에서는 JPA 와 Jooq 를 같이 사용해보자!

728x90