public class UserDTO {
private String name;
private int age;
// 생성자, getter, setter
public UserDTO(String name, int age) {
this.name = name;
this.age = age;
}
public String getName() { return name; }
public int getAge() { return age; }
}
✅ DTO의 역할
데이터만 담는 객체 (비즈니스 로직 없음)
UserDTO 객체는 Controller와 Service 사이에서 데이터를 주고받는 용도
getter가 있어야 JSON 변환이 가능함 (Spring에서 자동으로 JSON 응답으로 변환할 때 필요)
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
@RequestMapping("/user")
public class UserController {
private final UserService userService;
public UserController(UserService userService) {
this.userService = userService;
}
@GetMapping
public UserDTO getUser() {
return userService.getUser(); // DTO를 반환
}
}
✅ Controller의 역할
클라이언트의 요청을 처리하고 응답을 반환하는 역할
@RestController → JSON 형식으로 데이터를 반환하는 컨트롤러임을 명시
@GetMapping → /user 경로로 GET 요청이 오면 getUser() 메서드 실행
userService.getUser() 호출 → UserDTO를 받아서 JSON으로 변환해 응답
import org.springframework.stereotype.Service;
@Service
public class UserService {
public UserDTO getUser() {
return new UserDTO("Alice", 25); // DTO를 반환
}
}
✅ Service의 역할
비즈니스 로직 담당
예제에서는 간단하게 "Alice", 25 데이터를 UserDTO로 만들어 반환
실제 애플리케이션에서는 데이터베이스에서 사용자 정보를 가져와서 DTO로 변환하는 역할을 하게 됨
- GET /user 요청 → UserController.getUser()
- UserService.getUser() 호출 → UserDTO 생성
- UserDTO를 Controller에서 반환 → JSON 응답
{
"name": "Alice",
"age": 25
}