
1. 자바 설치 (Java JDK 17 이상 설치)
Java 8 (2014년 출시)
- 여전히 많은 기업에서 레거시 시스템으로 사용 중
- 람다 표현식, Stream API 등 중요한 기능이 도입된 버전
- 장기적으로는 점차 마이그레이션하는 추세
Java 11 (2018년 출시)
- 현재 가장 널리 채택되고 있는 LTS(Long Term Support) 버전
- Oracle의 상업적 지원이 필요 없는 OpenJDK 기반으로 무료 사용 가능
- 많은 새로운 프로젝트들이 Java 11을 기준으로 개발
Java 17 (2021년 출시)
- 최신 LTS 버전으로 채택률이 빠르게 증가하고 있음
- Spring Boot 3.0+ 등 주요 프레임워크들이 Java 17을 최소 요구사항으로 설정
https://wooncloud.tistory.com/160
Java 17 다운로드 방법
주요 Java 17 배포판1. Oracle JDK 17다운로드: https://www.oracle.com/java/technologies/javase/jdk17-archive-downloads.html특징: Oracle의 공식 배포판라이선스: 개발/테스트는 무료, 상업적 사용 시 유료2. Eclipse Adoptium다
wooncloud.tistory.com
2. Spring Boot 프로젝트 생성 (Gradle 버전)
https://start.spring.io 에서 다음과 같이 설정:
Project: Gradle - Groovy (또는 Gradle - Kotlin)
Language: Java
Spring Boot: 3.5.5 (포스팅 시점 안정적인 버전)
Group: com.example
Artifact: demo-api
Name: demo-api
Package name: com.example.demoapi
Packaging: Jar
Java: 17
Dependencies
- Spring Web
- Spring Boot DevTools
- Spring Data JPA
- PostgreSQL Driver ← PostgreSQL 연결용
- Thymeleaf
완료하고 zip 파일 다운로드.
3. IntelliJ에서 프로젝트 열기
- IntelliJ IDEA를 실행
- "Open" 버튼을 클릭 (또는 File > Open)
- 다운로드한 demo-api.zip을 압축 해제한 폴더를 선택
demo-api 폴더를 선택 > 폴더 안에 build.gradle 파일이 있는 폴더
IntelliJ가 프로젝트를 열고 Gradle 의존성을 다운로드함.
4. 첫 번째 실행 테스트
- 애플리케이션이 제대로 실행되는지 테스트.
- DemoApiApplication.java 파일에서 main 메소드 옆의 초록색 실행 버튼을 클릭해서 실행.
에러! PostgreSQL 설정을 안 했기 때문. => 이게 정상
5. docker로 데이터베이스 서버 오픈.
- https://www.docker.com/ 도커 다운로드.
- Docker Hub에서 postgres 검색
- pull 클릭.
- Images에서 pull 한 postgres image를 ▶️ 버튼 눌러서 실행.
- 그럼 컨테이너 이름과 포트, Environment variables 설정창이 나오는데 다음과 같이 입력.
- 컨테이너명: demo-db
- Host port: 5432
- Environment variables:
- Variable: POSTGRES_DB
- Value: demoapi
- Variable: POSTGRES_USER
- Value: demo
- Variable: POSTGRES_PASSWORD
- Value: demo123
Docker: Accelerated Container Application Development
Docker is a platform designed to help developers build, share, and run container applications. We handle the tedious setup, so you can focus on the code.
www.docker.com
아니면 아래 내용 복사해서 실행
docker run --name demo-db \
-e POSTGRES_DB=demoapi \
-e POSTGRES_USER=demo \
-e POSTGRES_PASSWORD=demo123 \
-p 5432:5432 \
-d postgres:15
6. src/main/resources/application.properties에 환경 세팅
src/main/resources/application.properties 에 아래의 내용 입력.
# PostgreSQL 데이터베이스 연결 설정
spring.datasource.url=jdbc:postgresql://localhost:5432/demoapi
spring.datasource.username=demo
spring.datasource.password=demo123
spring.datasource.driver-class-name=org.postgresql.Driver
# JPA 설정
spring.jpa.hibernate.ddl-auto=create-drop
spring.jpa.show-sql=true
spring.jpa.properties.hibernate.format_sql=true
설정 의미:
url: localhost의 9998 포트로 연결ddl-auto=create-drop: 애플리케이션 실행할 때마다 테이블 재생성 (개발용)show-sql=true: 실행되는 SQL 쿼리를 콘솔에 출력
7. 다시 실행
웹브라우저를 열어서 http://localhost:8080 에 접속.
결과: 아마 에러 페이지가 나올것임 (404 Not Found 같은) -> 정상
(아직 API 엔드포인트를 만들지 않았기 때문.)
8. 컨트롤러 작성
src/main/java/com/example/demo_api 위치에 HelloController.java 생성.
HelloController 클래스에 코드를 작성
package com.example.demoapi;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class HelloController {
@GetMapping("/hello")
public String hello() {
return "Hello, Spring Boot API!";
}
}
코드 설명:
- @RestController: 이 클래스가 REST API 컨트롤러라는 표시.
- @GetMapping("/hello"): GET 요청으로 /hello 경로에 매핑.
- return "Hello, Spring Boot API!": 응답으로 이 문자열을 반환.
테스트:
- 서버 재시작 후,
localhost:8080/hello에 접속 - "Hello, Spring Boot API!" 가 나오면 성공.
9. Thymeleaf 사용.
src/main/resources/templates위치에 index.html을 만듬.index.html에 아래 내용 입력:
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<title>Spring Boot + Thymeleaf</title>
<style>
body { font-family: Arial, sans-serif; margin: 40px; }
h1 { color: #2c3e50; }
.container { max-width: 600px; margin: 0 auto; }
.highlight { color: #e74c3c; font-weight: bold; }
</style>
</head>
<body>
<div class="container">
<h1>🌿 Thymeleaf 템플릿</h1>
<p>현재 시간: <span class="highlight" th:text="${currentTime}"></span></p>
<p>메시지: <span th:text="${message}"></span></p>
<ul>
<li><a href="/hello">텍스트 API</a></li>
<li><a href="/">Thymeleaf 템플릿</a></li>
</ul>
</div>
</body>
</html>
HelloController 수정
package com.example.demo_api;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ResponseBody;
@Controller
public class HelloController {
@GetMapping("/")
public String index(Model model) {
model.addAttribute("currentTime", java.time.LocalDateTime.now());
model.addAttribute("message", "Thymeleaf가 정상 작동중입니다!");
return "index";
}
@GetMapping("/hello")
@ResponseBody
public String hello() {
return "Hello, Spring Boot API!";
}
}
- @Controller: 뷰 템플릿을 반환할 수 있음
- @RestController: 항상 데이터(JSON/문자열)만 반환
- @ResponseBody: Controller에서 특정 메소드만 직접 데이터 반환
테스트
- http://localhost:8080/ 입력하면 🌿 Thymeleaf 템플릿 나와야함.
- http://localhost:8080/hello 는 여전히 "Hello, Spring Boot API!"가 나옴.
10. JPA Entity와 데이터베이스 연동
데이터베이스와 연동해서 CRUD API를 만들기.
1. 새로운 패키지 생성.
src/main/java/com/example/demo_api 안에 entity 패키지를 만들기.
- 우클릭 > New > Package >
entity입력
2. User Entity 클래스 생성.
entity 패키지에서 우클릭 > New > Java Class > User 입력
3. User.java에 다음 코드를 작성.
package com.example.demo_api.entity;
import jakarta.persistence.*;
@Entity
@Table(name = "users")
public class User {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@Column(nullable = false)
private String name;
@Column(nullable = false, unique = true)
private String email;
// 기본 생성자 (JPA 필수)
public User() {}
// 생성자
public User(String name, String email) {
this.name = name;
this.email = email;
}
// Getter, Setter
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
// toString 메소드 (디버깅용)
@Override
public String toString() {
return "User{" +
"id=" + id +
", name='" + name + '\'' +
", email='" + email + '\'' +
'}';
}
}
11. Repository 인터페이스 생성
repository패키지 생성src/main/java/com/example/demo_api안에repository패키지 만들기
UserRepository.java인터페이스 생성
package com.example.demo_api.repository;
import com.example.demo_api.entity.User;
import org.springframework.data.jpa.repository.JpaRepository;
public interface UserRepository extends JpaRepository<User, Long> {
// 기본 CRUD는 JpaRepository가 자동 제공
// findAll(), save(), findById(), deleteById() 등
}
12. User API Controller 생성
1. controller 패키지 생성
src/main/java/com/example/demo_api 안에 controller 패키지 만들기
2. 기존 HelloController.java를 controller 패키지로 이동
HelloController.java를 드래그해서controller패키지로 옮기고- 패키지 선언을
package com.example.demo_api.controller;로 수정
3. UserController.java 생성
controller 패키지에 새 클래스 생성하고 다음 코드 작성:
package com.example.demo_api.controller;
import com.example.demo_api.entity.User;
import com.example.demo_api.repository.UserRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import java.util.List;
@RestController
@RequestMapping("/api/users")
public class UserController {
@Autowired
private UserRepository userRepository;
// 모든 사용자 조회
@GetMapping
public List<User> getAllUsers() {
return userRepository.findAll();
}
}
여기서는 @RestController를 사용. JSON 데이터를 반환하기 위함!
13. 첫 번째 API 테스트
1. 애플리케이션 재시작
- IntelliJ에서 애플리케이션을 중지하고 다시 실행
2. API 테스트
- 브라우저에서 http://localhost:8080/api/users 에 접속
예상 결과
[]
DB에 사용자가 없어 빈 배열 나옴.
14. CRUD API 만들기 - 사용자 API 추가
UserController.java에 다음 메소드들을 추가
@RestController
@RequestMapping("/api/users")
public class UserController {
@Autowired
private UserRepository userRepository;
// 모든 사용자 조회
@GetMapping
public List<User> getAllUsers() {
return userRepository.findAll();
}
// 새 사용자 생성
@PostMapping
public User createUser(@RequestBody User user) {
return userRepository.save(user);
}
// 특정 사용자 조회
@GetMapping("/{id}")
public User getUserById(@PathVariable Long id) {
return userRepository.findById(id).orElse(null);
}
// 사용자 정보 수정
@PutMapping("/{id}")
public User updateUser(@PathVariable Long id, @RequestBody User userDetails) {
User user = userRepository.findById(id).orElse(null);
if (user != null) {
user.setName(userDetails.getName());
user.setEmail(userDetails.getEmail());
return userRepository.save(user);
}
return null;
}
// 사용자 삭제
@DeleteMapping("/{id}")
public String deleteUser(@PathVariable Long id) {
if (userRepository.existsById(id)) {
userRepository.deleteById(id);
return "사용자가 삭제되었습니다.";
}
return "사용자를 찾을 수 없습니다.";
}
}
- GET
/api/users- 모든 사용자 조회 - POST
/api/users- 사용자 생성 - GET
/api/users/{id}- 특정 사용자 조회 - PUT
/api/users/{id}- 사용자 정보 수정 - DELETE
/api/users/{id}- 사용자 삭제
15. 마무리
기본 CRUD API가 완성되면 다음 단계:
예외 처리 & 검증
@Valid어노테이션으로 데이터 검증- 전역 예외 처리 (
@ControllerAdvice) - 사용자 정의 예외 클래스
Service 계층 추가
- Controller-Service-Repository 아키텍처
- 비즈니스 로직 분리
@Service어노테이션
DTO (Data Transfer Object)
- Entity와 API 응답 분리
- 보안 강화 (민감한 필드 숨기기)
- ModelMapper 사용
관계형 데이터베이스
- 다른 Entity 추가 (예: Post, Comment)
- JPA 관계 매핑 (
@OneToMany,@ManyToOne) - 복잡한 쿼리
API 문서화
- Swagger/OpenAPI 추가
- API 문서 자동 생성
'개발 아카이브 > JAVA' 카테고리의 다른 글
| Spring 기본 - DTO (Data Transfer Object) 패턴 (0) | 2025.09.20 |
|---|---|
| Spring 기본 - Service 계층 (0) | 2025.09.20 |
| Java 17 다운로드 방법 (0) | 2025.09.03 |
| [Spring] @Autowired를 지혜롭게 하는 법. (0) | 2021.10.21 |
| [Spring] 스케줄러 Cron 사용하기 (1) | 2021.08.10 |