spring boot

Spring Boot, React 연동하기

소리소리솔소리 2023. 2. 15. 11:14

Spring Boot 프로젝트 생성

https://start.spring.io 

  • 언어 : Java
  • Type : Gradle-Groovy
  • Group : com.**** (회사이름?)
  • Artifact : SpringReact (해당 프로젝트명)
  • JDK : 11
  • Java : 11
  • Packaging : Jar

Dependency (필요한 의존성 추가하기)

  • Spring Boot DevTools
  • Lombok
  • Spring Web
  • Thymeleaf 
  • Spring Data JPA
  • WebSocket
  • MySQL Driver
  • Oracle Driver

 

- Port 변경

src > main > reources > application.properties

server.port=8090

 

- CORS 어노테이션 방법

@CrossOrigin(origins = "<http://localhost:3000>")

 

- JDBC 연결

src > main > reources > application.properties

server.port=8090

spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
spring.datasource.url=jdbc:mysql://localhost:3306/스키마이름?userUnicode=true&characterEncoding=UTF-8&serverTimezone=Asia/Seoul
spring.datasource.username=
spring.datasource.password=

http://localhost:8090에 에러페이지가 보이면 OK

 

 

React : src/main/frontend 생성

  • cd src/main
  • yarn create react-app frontend

 

관련 모듈 설치

  • yarn add axios styled-component react-router-dom

 

- build.gradle 파일 하단에 코드 추가

def frontendDir = "$projectDir/src/main/frontend"

sourceSets {
    main {
        resources { srcDirs = ["$projectDir/src/main/resources"]
        }
    }
}

processResources { dependsOn "copyReactBuildFiles" }

task installReact(type: 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'
    }
}

task buildReact(type: 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"
    }
}

task copyReactBuildFiles(type: Copy) {
    dependsOn "buildReact"
    from "$frontendDir/build"
    into "$projectDir/src/main/resources/static"
}

 

- gradle 빌드 시 jar 파일이 2개 만들어지는 문제 수정 (build.gradle에 추가)

jar {
    enabled = false
}

 

- 홈 디렉토리로 빠져나와 빌드 실행

./gradlew build

 

- BUILD SUCCESSFUL 메세지가 보인다면, build/libs 폴더에 jar 파일로 결과물이 생성됨

- 실행하기

java -jar build\libs\*******-0.0.1-SNAPSHOT.jar

'spring boot' 카테고리의 다른 글

Spring Boot @Builder  (0) 2023.03.14
Spring Boot Thymeleaf Caching(템플릿 캐싱)  (0) 2023.03.13
Window 환경에서 JDK 설치 & 환경변수 설정  (0) 2023.03.07
Spring Boot  (0) 2022.11.04