Spring/SpringBoot-React
SpringBoot + React 연동(1) - 스프링부트 + React 설치
ChrisMare
2023. 8. 24. 14:55
개발 환경
- IDE (통합개발환경)
- IntelliJ Community, Visual Studio Code
개발 언어
- JAVA 11
프레임워크
- Spring Boot
라이브러리
- React.js
1. Node.js 다운 ( 안정적인 LTS를 받거나, 혹은 사용하려는 React 버전에 맞춰서 다운 )
- Java Script Runtime Environment
- NPM(Node Package Manager)을 활용한 모듈 다운 용도
- 주의: 자신의 운영체제에 맞게 다운
2. 스프링 부트 프로젝트 생성
- Project: Gradle - Groovy
- Language: Java
- Spring Boot: 2.7.14 ( JAVA 11 )
- Project Metadata
- Group: com.react (회사내에서는 정해진 정책에 따라서 설정)
- Artifact: exam ( 프로젝트명 )
- Packaging: Jar
- Java: 11
- Dependencies
- Spring Web (웹 어플리케이션 개발지원)
- MariaDB Driver
- Lombok ( getter, setter, contructor 주입 등 자동 생성 개발편의성 지원 )
GENERATE 클릭 해서 Zip 다운
다운 받은 Zip 파일을 풀면 exam(프로젝트명)이 나온다.
IntelliJ IDE 오픈
3. Open -> exam(artifact명) -> build.gradle 선택 후 Open As Project
4. 기본 설정
Settings -> Gradle검색 -> Gradle
- Build and run using: IntelliJ IDEA 로 변경
- Run tests using: IntelliJ IDEA 로 변경
- 변경하는 이유는 Gradle 로 실행시 Gradle를 거치고 실행되기 때문에 속도가 느리기 때문에 바로 IDEA 실행하려는 이유입니다.
5. 실행 테스트 (http://localhost:8080/)
스프링 부트 장점: 이전 dependency에 Spring Web을 설치해서 톰캣이 이미 내장되어 있기 때문에 따로 톰캣등의 서버를 설정할 필요가 없다.
오류 페이지가 나온다면 정상!
6. 리액트 설치 및 연동
- Terminal Open
- cd src/main
- npx create-react-app front(view 프로젝트명)
- cd front
- npm start
- 설치 후 확인 http://localhost:3000/
7. 스프링 부트와 리액트 포트연동
- 프론트(3000)와 백엔드 서버(8080) 포트가 다르니 포트를 통합해야된다.
- 프론트 설정
- src/main/front/package.json
- "proxy": "http://localhost:8080" (Proxy설정 임의로 서버포트 연결)
2. 백엔드 설정
- build.gradle 파일의 맨 밑에 아래 설정 추가
- 설정 추가 후 파란색 코끼리 아이콘 클릭
- Tasks -> build -> build 클릭!
- 빌드 완료 ExamApplication.java 서버 재실행 (주의: Gradle를 했기때문에 변경되있어서 ExamApplication 변경필요)
- http://localhost:8080/ (접속해서 연동됐는지 확인!)
- 이제 3000번 포트의 리액트와 8080포트의 스프링부트가 연동됨을 확인할 수 있다!
def frontendDir = "$projectDir/src/main/front"
sourceSets {
main {
resources { srcDirs = ["$projectDir/src/main/resources"]
}
}
}
processResources { dependsOn "copyReactBuildFiles" }
tasks.register('installReact', Exec) {
workingDir "$frontendDir"
inputs.dir "$frontendDir"
group = BasePlugin.BUILD_GROUP
if (System.getProperty('os.name').toLowerCase(Locale.ROOT).contains('windows')) {
commandLine "npm.cmd", "audit", "fix"
commandLine 'npm.cmd', 'install'
} else {
commandLine "npm", "audit", "fix" commandLine 'npm', 'install'
}
}
tasks.register('buildReact', Exec) {
dependsOn "installReact"
workingDir "$frontendDir"
inputs.dir "$frontendDir"
group = BasePlugin.BUILD_GROUP
if (System.getProperty('os.name').toLowerCase(Locale.ROOT).contains('windows')) {
commandLine "npm.cmd", "run-script", "build"
} else {
commandLine "npm", "run-script", "build"
}
}
tasks.register('copyReactBuildFiles', Copy) {
dependsOn "buildReact"
from "$frontendDir/build"
into "$projectDir/src/main/resources/static"
}
이제 기본적으로 스프링 부트와 리액트가 연동이 끝났습니다.
감사합니다!