이 튜토리얼에서는 Spring Boot와 Gradle를 사용하여 간단한 RESTful 웹 서비스를 만들어 보겠습니다. Spring Boot는 독립적이고 프로덕션 등급의 Spring 기반 애플리케이션을 쉽게 만들 수 있게 해주며, Gradle은 빌드 프로세스를 단순화하는 강력한 빌드 도구입니다.
REST란 무엇인가?
REST, 표현 상태 전달은 API가 상호 운용 가능하고 확장 가능하며 유지 보수가 가능하도록 하는 일련의 아키텍처 원칙입니다. 레고 블록을 만드는 것을 상상해보세요. 다른 애플리케이션들은 RESTful 가이드라인을 따르는 한 서로 원활하게 API와 상호 작용할 수 있습니다. 이는 레고의 세트와 상관없이 블록들이 함께 클릭되는 것과 같습니다.
Spring Boot란 무엇인가?
Spring Boot 는 개발 과정을 단순화하는 강력한 프레임워크입니다. 이를 미리 구축된 툴킷으로 생각하세요. 이 툴킷에는 구성 요소와 기능이 가득하여 애플리케이션 인프라를 설정하는 데 시간과 노력을 절약해 줍니다. API의 핵심 로직을 만들 때 번거로운 코드에 얽매이지 않고 집중할 수 있습니다.
API 개발자의 잠재력을 발휘할 준비가 되셨나요? 이 가이드는 인기 있는 빌드 도구인 Gradle를 사용하여 첫 번째 Spring Boot REST 애플리케이션을 만드는 데 필요한 핵심 지식을 제공합니다. 경력이 많은 Java 프로그래머이든 탐색을 시작하는 초보자든, 이 단계별 여정은 동적이고 상호 작용적인 웹 서비스를 구축하는 데 필요한 기본 지식을 제공합니다.
주요 통찰력
- RESTful API 개발을 위한 Spring Boot 사용하기: Spring Boot는 RESTful API 개발 과정을 단순화하는 인기 있는 Java 프레임워크입니다. 자동 구성과 의존성 주입과 같은 다양한 기능을 기본적으로 제공하므로, 시간과 노력을 절약할 수 있습니다.
- RESTful API의 핵심 개념 이해하기: REST는 Representational State Transfer의 약자입니다. 이는 API가 상호 운용 가능하고 확장 가능하며 유지 보수가 용이하도록 하는 일련의 아키텍처 원칙입니다. RESTful API의 주요 개념에는 리소스 표현, HTTP 메서드 및 상태 코드가 포함됩니다.
- 기본 CRUD 작업 구현하기: CRUD는 Create, Read, Update, Delete를 의미합니다. 이는 사용자가 데이터와 상호 작용할 수 있도록 API 엔드포인트에서 구현해야 할 기본 작업입니다.
- API를 철저히 테스트하기: 생산 환경에 API를 배포하기 전에 철저한 테스트를 수행하는 것이 중요합니다. 이를 통해 예상대로 작동하고 버그가 없는지 확인할 수 있습니다.
- 고급 기능 탐색하기: Spring Boot와 RESTful API에 더 익숙해지면 데이터 관리, 보안, 인증과 같은 고급 기능을 탐색할 수 있습니다.
REST의 힘과 Spring Boot의 간결한 접근 방식을 결합하여 다른 애플리케이션과 원활하게 통합되는 효율적이고 사용자 친화적인 API를 만들 수 있습니다. 그래서 Spring Boot와 Gradle로 RESTful API의 잠재력을 활용할 준비가 되셨나요? 시작합시다!
사전 요건
- Java Development Kit (JDK) 11 설치
- Gradle의 최신 버전 설치
- Java 및 Spring 개념의 기본적인 이해
1단계: 프로젝트 설정
프로젝트를 시작하려면 다음 3단계를 시작해야 합니다.
- 터미널 또는 명령 프롬프트를 엽니다.
- 프로젝트를 위한 새 디렉토리를 생성합니다.
- 프로젝트 디렉토리로 이동합니다.
- 기본 스프링 부트 프로젝트 구조를 초기화합니다.
mkdir spring-boot-rest-gradle
cd spring-boot-rest-gradle
gradle init --type spring-boot
2단계: 스프링 부트 프로젝트 생성
디렉토리에 있는 기존 build.gradle 파일을 다음 내용으로 편집하십시오.
plugins {
id 'org.springframework.boot' version '2.6.3'
id 'io.spring.dependency-management' version '1.0.11.RELEASE'
id 'java'
}
group = 'com.example'
version = '1.0-SNAPSHOT'
sourceCompatibility = '11'
repositories {
mavenCentral()
}
dependencies {
implementation 'org.springframework.boot:spring-boot-starter-web'
testImplementation 'org.springframework.boot:spring-boot-starter-test'
}
test {
useJUnitPlatform()
}
이것은 필요한 의존성을 포함하여 기본 스프링 부트 프로젝트를 설정합니다.
3단계: REST 컨트롤러 생성
다음 내용으로 src/main/java/com/example 디렉토리에 HelloController.java라는 새 파일을 생성하십시오:
import org.springframework.web.bind.annotation.*;
import java.util.ArrayList;
import java.util.List;
@RestController
@RequestMapping("/api")
public class HelloController {
private final List<String> messages = new ArrayList<>();
@GetMapping("/hello")
public String sayHello() {
return "Hello, Spring Boot!";
}
@GetMapping("/messages")
public List<String> getMessages() {
return messages;
}
@PostMapping("/messages")
public String addMessage(@RequestBody String message) {
messages.add(message);
return "Message added: " + message;
}
@PutMapping("/messages/{index}")
public String updateMessage(@PathVariable int index, @RequestBody String updatedMessage) {
if (index < messages.size()) {
messages.set(index, updatedMessage);
return "Message updated at index " + index + ": " + updatedMessage;
} else {
return "Invalid index";
}
}
@DeleteMapping("/messages/{index}")
public String deleteMessage(@PathVariable int index) {
if (index < messages.size()) {
String removedMessage = messages.remove(index);
return "Message removed at index " + index + ": " + removedMessage;
} else {
return "Invalid index";
}
}
}
이것은 간단한 메시지 목록에 대한 GET, POST, PUT, DELETE 작업을 위한 엔드포인트를 가진 REST 컨트롤러를 정의합니다.
4단계: 애플리케이션 실행
터미널 또는 명령 프롬프트를 열고 다음 명령을 실행하십시오:
./gradlew bootRun
브라우저에서 http://localhost:8080/api/hello를 방문하여 초기 엔드포인트를 확인하십시오. curl, Postman 또는 다른 REST 클라이언트 도구를 사용하여 다른 엔드포인트를 테스트할 수 있습니다.
5단계: 테스트 케이스 작성
HelloControllerTest.java 파일을 src/test/java/com/example 디렉토리에 다음 내용으로 생성하세요:
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.BeforeEach;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.http.MediaType;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.request.MockMvcRequestBuilders;
import org.springframework.test.web.servlet.result.MockMvcResultMatchers;
import static org.hamcrest.Matchers.hasSize;
import static org.hamcrest.Matchers.is;
@SpringBootTest
@AutoConfigureMockMvc
public class HelloControllerTest {
@Autowired
private MockMvc mockMvc;
@BeforeEach
public void setUp() {
// 각 테스트 전에 메시지를 지우기
// 이는 각 테스트에 대한 깨끗한 상태를 보장합니다
// 또는 요구 사항에 따라 테스트 데이터베이스나 목 데이터를 사용할 수도 있습니다
// 요구 사항에 따라
HelloController messagesController = new HelloController();
messagesController.getMessages().clear();
}
@Test
public void testSayHello() throws Exception {
mockMvc.perform(MockMvcRequestBuilders.get("/api/hello"))
.andExpect(MockMvcResultMatchers.status().isOk())
.andExpect(MockMvcResultMatchers.content().string("Hello, Spring Boot!"));
}
@Test
public void testGetMessages() throws Exception {
mockMvc.perform(MockMvcRequestBuilders.get("/api/messages"))
.andExpect(MockMvcResultMatchers.status().isOk())
.andExpect(MockMvcResultMatchers.jsonPath("$", hasSize(0)));
}
@Test
public void testAddMessage() throws Exception {
mockMvc.perform(MockMvcRequestBuilders.post("/api/messages")
.contentType(MediaType.APPLICATION_JSON)
.content("\"Test Message\""))
.andExpect(MockMvcResultMatchers.status().isOk())
.andExpect(MockMvcResultMatchers.content().string("Message added: Test Message"));
}
@Test
public void testUpdateMessage() throws Exception {
mockMvc.perform(MockMvcRequestBuilders.post("/api/messages")
.contentType(MediaType.APPLICATION_JSON)
.content("\"Initial Message\""));
mockMvc.perform(MockMvcRequestBuilders.put("/api/messages/0")
.contentType(MediaType.APPLICATION_JSON)
.content("\"Updated Message\""))
.andExpect(MockMvcResultMatchers.status().isOk())
.andExpect(MockMvcResultMatchers.content().string("Message updated at index 0: Updated Message"));
}
@Test
public void testDeleteMessage() throws Exception {
mockMvc.perform(MockMvcRequestBuilders.post("/api/messages")
.contentType(MediaType.APPLICATION_JSON)
.content("\"Message to Delete\""));
mockMvc.perform(MockMvcRequestBuilders.delete("/api/messages/0"))
.andExpect(MockMvcResultMatchers.status().isOk())
.andExpect(MockMvcResultMatchers.content().string("Message removed at index 0: Message to Delete"));
}
}
이 테스트 케이스들은 Spring Boot의 테스트 기능을 사용하여 HTTP 요청을 시뮬레이션하고 REST 컨트롤러의 동작을 확인합니다.
6단계: 테스트 실행
터미널이나 명령 프롬프트를 열고 테스트를 실행하기 위해 다음 명령어를 실행하세요:
./gradlew test
모든 테스트가 성공적으로 통과하는지 테스트 결과를 검토하세요.
결론
축하합니다! 이 튜토리얼에서는 Spring Boot와 Gradle을 사용하여 CRUD 작업을 위한 기본적인 RESTful 웹 서비스를 성공적으로 생성하였습니다. GET, POST, PUT, DELETE 작업을 위한 엔드포인트의 구현과 해당하는 테스트 케이스에 대해 다루었습니다.
추가 메모:
- 이것은 매우 기본적인 예입니다. 더 많은 엔드포인트를 생성하고, 다양한 HTTP 메서드(POST, PUT, DELETE)를 처리하며, 데이터 관리와 같은 기능을 추가하여 확장할 수 있습니다.
- JUnit과 같은 프레임워크를 사용하여 컨트롤러에 대한 단위 테스트를 고려하십시오.
- 추가적인 의존성과 설정을 포함한 프로젝트를 신속하게 생성하려면 Spring Initializr(https://start.spring.io/)를 사용하십시오.
추가 학습을 위해 다음 리소스를 확인하세요:
- Spring Boot 시작 가이드: https://spring.io/guides/gs/spring-boot/
- Spring REST 서비스 자습서: https://spring.io/guides/gs/rest-service/
- Spring Boot Actuator로 RESTful 웹 서비스 구축: https://spring.io/guides/gs/actuator-service/
기억하세요, 이것은 단지 Spring Boot 여정의 시작일 뿐입니다! 놀라운 애플리케이션을 만들며 계속 탐색하세요.
Source:
https://dzone.com/articles/build-your-first-spring-boot-rest-application-with