프로그래밍 공부
Spring Boot를 사용하여 Hello World API 빌드하기 본문
🚀 Spring Boot로 Hello World API 만들기
Spring Boot를 사용하면 빠르고 쉽게 REST API를 개발할 수 있어! 이번 가이드를 통해 Hello World API를 만들고 실행하는 방법을 알아보자.
1️⃣ 프로젝트 생성
📌 Spring Initializr를 이용한 프로젝트 생성
Spring Boot 프로젝트를 생성하는 방법에는 여러 가지가 있지만, 가장 쉬운 방법은 Spring Initializr를 이용하는 것.
✅ 설정 예시
- Project: Gradle / Maven
- Language: Java
- Spring Boot: 최신 버전 선택
- Dependencies:
- Spring Web (REST API 개발을 위해 필요)
- Packaging: Jar
- Java Version: 17 (또는 최신 버전)
📌 [Generate] 버튼을 눌러 프로젝트 다운로드 후 압축을 풀고 IDE에서 열기
2️⃣ 프로젝트 구조
📁 프로젝트 구조는 다음과 같다.
my-hello-world
├── src
│ ├── main
│ │ ├── java/com/example/helloworld
│ │ │ ├── HelloWorldApplication.java // 메인 클래스
│ │ │ ├── controller
│ │ │ │ ├── HelloController.java // REST 컨트롤러
│ ├── test
├── build.gradle (또는 pom.xml)
3️⃣ Hello World API 만들기
📌 1. 메인 클래스 생성
Spring Boot 애플리케이션을 실행할 메인 클래스를 만든다.
package com.example.helloworld;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class HelloWorldApplication {
public static void main(String[] args) {
SpringApplication.run(HelloWorldApplication.class, args);
}
}
📌 2. 컨트롤러(Controller) 생성
HTTP 요청을 처리할 컨트롤러 클래스를 생성한다.
package com.example.helloworld.controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
@RequestMapping("/api")
public class HelloController {
@GetMapping("/hello")
public String hello() {
return "Hello, World!";
}
}
📌 설명
- @RestController → RESTful API 컨트롤러임을 선언
- @RequestMapping("/api") → API의 기본 경로 설정
- @GetMapping("/hello") → GET /api/hello 요청을 받으면 "Hello, World!" 반환
4️⃣ 실행 및 테스트
📌 1. 프로젝트 실행
터미널 또는 IDE에서 다음 명령어 실행:
./gradlew bootRun # (Gradle 사용 시)
mvn spring-boot:run # (Maven 사용 시)
📌 2. API 테스트
브라우저 또는 Postman을 이용해서 API 호출:
<http://localhost:8080/api/hello>
📌 응답 결과
Hello, World!
5️⃣ 추가 설정 (선택)
1️⃣ application.properties 설정
기본 포트를 변경하고 싶다면 src/main/resources/application.properties에서 설정 가능
server.port=9090
👉 이제 http://localhost:9090/api/hello에서 API를 호출할 수 있음!
🎯 정리
✅ Spring Boot 프로젝트를 생성하고 HelloController를 만들면 쉽게 REST API 개발 가능
✅ /api/hello 요청을 처리하는 컨트롤러를 작성하고 실행하면 API 응답 확인 가능
✅ 추가적으로 포트 변경 등 application.properties에서 설정 가능
이제 Spring Boot를 사용해서 더 다양한 API를 만들어볼 수 있다! 🚀🔥
'Programming > Spring' 카테고리의 다른 글
Spring Boot - Actuator (0) | 2025.02.11 |
---|---|
Spring Boot Properties - Profile, ConfigurationProperties (1) | 2025.02.11 |
Spring Boot를 사용하는 이유와 스프링 프레임워크와의 차이 (0) | 2025.02.11 |
Spring 전체 구조 알아보기(주요 모듈) 및 정리 (0) | 2025.02.10 |
스테레오 타입 어노테이션(Stereotype Annotation) (0) | 2025.02.10 |
Comments