본문 바로가기
Framework/Spring

[Spring Boot] 계층형 아키텍처 정리

by 챠챠12 2024. 10. 15.
728x90
반응형
SMALL

 Controller, Service, ReqDTO, ResDTO 구조는 계층형 아키텍처를 따르는 전형적인 설계 방식입니다.

 

1. Controller:

  • 역할: 사용자의 요청(Request)을 처리하고, 적절한 서비스 호출 및 결과를 반환(Response)하는 역할을 합니다. 주로 HTTP 요청을 매핑하고, URL 경로에 따라 어떤 서비스를 호출할지 결정합니다.
  • 위치: Spring Boot의 MVC 패턴에서 컨트롤러는 주로 @RestController 또는 @Controller로 정의됩니다.
@RestController
@RequestMapping("/api/example")
public class ExampleController {

    private final ExampleService exampleService;

    public ExampleController(ExampleService exampleService) {
        this.exampleService = exampleService;
    }

    @PostMapping("/create")
    public ResponseEntity<ResDTO> create(@RequestBody ReqDTO reqDTO) {
        ResDTO response = exampleService.create(reqDTO);
        return ResponseEntity.ok(response);
    }
}

2. Service:

  • 역할: 비즈니스 로직을 처리하는 레이어입니다. 컨트롤러로부터 전달받은 데이터를 가공하거나 여러 DAO(repository) 또는 외부 API 호출 등을 수행하여 요청을 처리합니다.
  • 위치: @Service로 정의되며, 주로 컨트롤러와 데이터 액세스 레이어(Repository) 사이에서 동작합니다.
@Service
public class ExampleService {

    private final ExampleRepository exampleRepository;

    public ExampleService(ExampleRepository exampleRepository) {
        this.exampleRepository = exampleRepository;
    }

    public ResDTO create(ReqDTO reqDTO) {
        // 비즈니스 로직 처리
        ExampleEntity entity = new ExampleEntity(reqDTO.getData());
        exampleRepository.save(entity);
        
        // 처리 후 결과 반환
        return new ResDTO(entity.getId(), "성공적으로 생성되었습니다.");
    }
}

3. ReqDTO (Request Data Transfer Object):

  • 역할: 클라이언트가 전송하는 요청 데이터를 담는 객체입니다. 주로 클라이언트에서 넘어오는 데이터를 검증하고, 서비스 레이어로 전달하는 용도로 사용됩니다.
  • **DTO (Data Transfer Object)**는 주로 HTTP 요청과 응답 간의 데이터 캡슐화에 사용됩니다.
  • 위치: @RequestBody로 컨트롤러에서 받아들여 서비스로 전달합니다.
public class ReqDTO {
    private String data;

    // Getters and Setters
    public String getData() {
        return data;
    }

    public void setData(String data) {
        this.data = data;
    }
}

4. ResDTO (Response Data Transfer Object):

  • 역할: 서비스 계층에서 처리된 결과를 컨트롤러로 전달하여, 클라이언트에게 응답할 데이터를 담는 객체입니다.
  • 위치: 서비스에서 생성되고, 컨트롤러를 통해 클라이언트로 반환됩니다.
public class ResDTO {
    private Long id;
    private String message;

    // Constructor
    public ResDTO(Long id, String message) {
        this.id = id;
        this.message = message;
    }

    // Getters and Setters
    public Long getId() {
        return id;
    }

    public void setId(Long id) {
        this.id = id;
    }

    public String getMessage() {
        return message;
    }

    public void setMessage(String message) {
        this.message = message;
    }
}

구조 요약:

  • Controller: 요청을 받아 서비스 호출. 클라이언트 요청과 응답 처리.
  • Service: 비즈니스 로직을 처리하는 핵심 레이어. 데이터베이스 접근, 외부 API 호출 등 수행.
  • ReqDTO: 클라이언트에서 받은 요청 데이터를 담는 객체.
  • ResDTO: 클라이언트에게 응답할 데이터를 담는 객체.

이 구조는 각 레이어가 명확하게 분리되어 유지보수와 확장성이 높습니다.

 

728x90
반응형
SMALL

댓글