Spring Boot와 React를 사용하여 간단한 웹 애플리케이션을 구축하는 방법을 소개하겠습니다.
백엔드는 Kotlin으로 구현하고, 프론트엔드는 React로 구성합니다.
프로젝트 구조
demo/
├── backend/
│ ├── src/
│ │ ├── main/
│ │ │ ├── kotlin/
│ │ │ │ └── com/
│ │ │ │ └── example/
│ │ │ │ └── demo/
│ │ │ │ ├── DemoApplication.kt
│ │ │ │ └── controllers/
│ │ │ │ └── ExampleController.kt
│ │ │ └── resources/
│ │ │ └── application.properties
│ │ └── test/
│ │ ├── kotlin/
│ │ └── resources/
│ ├── build.gradle.kts
│ ├── settings.gradle.kts
├── frontend/
│ ├── public/
│ ├── src/
│ │ ├── api.ts
│ │ ├── App.tsx
│ │ └── index.tsx
│ ├── package.json
│ ├── tsconfig.json
│ └── .env
├── .gitignore
└── README.md
백엔드 설정 (Spring Boot + Kotlin)
1. Spring Initializr로 프로젝트 생성
Spring Initializr(https://start.spring.io/)를 사용하여 프로젝트를 생성합니다.
- Project: Gradle Project
- Language: Kotlin
- Spring Boot: 최신 안정 버전
- Project Metadata:
- Group: com.example
- Artifact: demo
- Name: demo
- Package name: com.example.demo
- Packaging: Jar
- Java: 11 (또는 최신 LTS)
- Dependencies:
- Spring Web
- Spring Boot DevTools
2. build.gradle.kts 설정
backend/build.gradle.kts 파일을 다음과 같이 설정합니다.
plugins {
id("org.springframework.boot") version "3.3.0"
id("io.spring.dependency-management") version "1.0.11.RELEASE"
kotlin("jvm") version "1.6.21"
kotlin("plugin.spring") version "1.6.21"
}
group = "com.example"
version = "0.0.1-SNAPSHOT"
java.sourceCompatibility = JavaVersion.VERSION_11
repositories {
mavenCentral()
}
dependencies {
implementation("org.springframework.boot:spring-boot-starter-web")
implementation("com.fasterxml.jackson.module:jackson-module-kotlin")
implementation("org.jetbrains.kotlin:kotlin-reflect")
implementation("org.jetbrains.kotlin:kotlin-stdlib-jdk8")
testImplementation("org.springframework.boot:spring-boot-starter-test")
}
tasks.withType<KotlinCompile> {
kotlinOptions {
freeCompilerArgs = listOf("-Xjsr305=strict")
jvmTarget = "11"
}
}
tasks.withType<Test> {
useJUnitPlatform()
}
3. DemoApplication.kt 설정
backend/src/main/kotlin/com/example/demo/DemoApplication.kt 파일을 생성하고 다음과 같이 설정합니다.
package com.example.demo
import org.springframework.boot.autoconfigure.SpringBootApplication
import org.springframework.boot.runApplication
import org.springframework.context.annotation.Bean
import org.springframework.web.servlet.config.annotation.CorsRegistry
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer
@SpringBootApplication
class DemoApplication {
@Bean
fun corsConfigurer(): WebMvcConfigurer {
return object : WebMvcConfigurer {
override fun addCorsMappings(registry: CorsRegistry) {
registry.addMapping("/**").allowedOrigins("http://localhost:3000")
}
}
}
}
fun main(args: Array<String>) {
runApplication<DemoApplication>(*args)
}
4. 간단한 컨트롤러 작성
backend/src/main/kotlin/com/example/demo/controllers/ExampleController.kt 파일을 생성하고 다음과 같이 설정합니다.
package com.example.demo.controllers
import org.springframework.web.bind.annotation.GetMapping
import org.springframework.web.bind.annotation.RequestMapping
import org.springframework.web.bind.annotation.RestController
@RestController
@RequestMapping("/api/example")
class ExampleController {
@GetMapping
fun getExample(): List<String> {
return listOf("Hello", "World")
}
}
프론트엔드 설정 (React)
1. Create React App으로 프로젝트 생성
터미널에서 frontend 디렉토리로 이동한 후 React 프로젝트를 생성합니다.
npx create-react-app frontend --template typescript
2. 필요한 패키지 설치
React에서 Axios를 사용하여 백엔드와 통신할 수 있도록 필요한 패키지를 설치합니다.
cd frontend
npm install axios
3. Axios 설정
frontend/src/api.ts 파일을 생성하고 다음과 같이 설정합니다.
import axios from 'axios';
const api = axios.create({
baseURL: process.env.REACT_APP_BACKEND_URL || 'http://localhost:8080/api',
});
export default api;
4. 환경 변수 설정
프로젝트 루트 디렉토리에 .env 파일을 생성하고 다음 내용을 추가합니다.
REACT_APP_BACKEND_URL=http://localhost:8080/api
5. 간단한 컴포넌트 작성
frontend/src/App.tsx 파일을 다음과 같이 수정합니다.
import React, { useEffect, useState } from 'react';
import api from './api';
const App: React.FC = () => {
const [data, setData] = useState<string[]>([]);
useEffect(() => {
api.get('/example')
.then(response => {
setData(response.data);
})
.catch(error => {
console.error("There was an error fetching the data!", error);
});
}, []);
return (
<div className="App">
<h1>Demo Project</h1>
<ul>
{data.map((item, index) => (
<li key={index}>{item}</li>
))}
</ul>
</div>
);
}
export default App;
프로젝트 실행
백엔드 실행
백엔드(Spring Boot) 서버를 실행합니다. 이클립스 또는 인텔리j에서 실행
프론트엔드 실행
프론트엔드(React) 애플리케이션을 실행합니다.
cd frontend
npm start
마무리
이제 브라우저에서 http://localhost:3000을 열어 React 애플리케이션이 Spring Boot 백엔드와 올바르게 통신하는지 확인할 수 있습니다.
'Spring & Spring Boot' 카테고리의 다른 글
[Spring Boot] CORS의 기본 개념 (0) | 2024.06.16 |
---|---|
[ Spring Boot Kotiln ] Redis 사용하기 (0) | 2024.02.25 |
[ JPA ] batch_fetch_size (0) | 2024.02.21 |
[Spring Boot] Kotlin Ktlint 적용하기 (2) | 2024.01.21 |
[ Spring Cloud ] Spring Cloud Netflix Eureka - 2편 (0) | 2021.07.15 |