개발 기록/Java

[Springboot] 기본작업 #2 - 이클립스에서 프로젝트 생성과 의존성 설정

JasonM 2023. 5. 21. 01:45
반응형

 

이클립스에서 개발환경 세팅이 완료되면 Spring Boot Project를 생성할 수 있다. 여기서는 이클립스에서 신규 프로젝트 생성하는 방법과 gradle.build 파일을 통해 Java 기반 프로그램의 의존성을 설정하는 방법을 알아보자.  
 

Spring Boot 신규 프로젝트 생성 


[Eclipse 상단 메뉴] → [File] → [New] → [Others..] 에서 Spring Starter Project를 선택해서 신규 프로젝트를 만든다.
Ctrl + N 단축키로도 신규 프로젝트 생성 창을 열 수 있다.
 

이클립스 신규 프로젝트 생성 창

 
 
Next를 누르면 아래와 같은 정보를 입력하는데 Name, Java 버전, Build Typ, Packing 등을 설정 후 다음으로 이동.

  • Name: [프로젝트 명]
  • Build Type: Gradle
  • Java Version: 8
  • Packaging: War
  • Package: [패키지 명]
     

이클립스 Springboot 프로젝트 첫 번째 설정 창

 
다음으로 넘어가면 Dependency를 묻는 창이 나오는데, 필요한 패키지들을 프로젝트 생성 시 알아서 추가해 준다. 
하지만 기존 프로젝트에서 Dependency를 복사해 올 것이기 때문에 선택하지 않고 Next를 눌러 다음으로 넘어간다.

 

Finish를 눌러서 프로젝트를 생성을 완료해도 된다.

이클립스 Springboot 프로젝트 두 번째 설정 창

 

위에서 Finish를 누르지 않고 Next를 눌렀을 경우 아래 화면이 나오는데, Site 관련 정보인 것 같다. Default 값 그대로 둔 채 Finish를 눌러서 프로젝트 생성.

이클립스 Springboot 프로젝트 세 번째 설정 창

 
 
Spring Boot 프로젝트를 생성하고 나면 아래와 같이 왼쪽 Project Explorer에서 생성된 프로젝트를 확인할 수 있다.
 

이클립스 Springboot 프로젝트 생성 이후 창

 
 
 


반응형

build.gradle 설정


의존성을 설정하기 위해서는 build.gradle 파일을 변경해야 한다. 다만, Spring Boot Gradle 프로젝트가 정상적으로 생성된 줄 알았는데, 위 스크린 샷과 같이 프로젝트 명에 에러가 표시되어 있었다. 일단 프로젝트가 생성이 되기는 했지만, 고작 폴더 2개와 Gradle 관련 몇 가지 파일만 보여서 에러부터 해결하고 넘어가야 했다.

Gradle 빌드 에러

CONFIGURE SUCCESSFUL in 3s

FAILURE: Build failed with an exception.

* What went wrong:
A problem occurred configuring root project 'jsonm_dev_demo'.
> Could not resolve all files for configuration ':classpath'.
   > Could not resolve org.springframework.boot:spring-boot-gradle-plugin:3.0.7.
     Required by:
         project : > org.springframework.boot:org.springframework.boot.gradle.plugin:3.0.7
      > No matching variant of org.springframework.boot:spring-boot-gradle-plugin:3.0.7 was found. The consumer was configured to find a runtime of a library compatible with Java 8, packaged as a jar, and its dependencies declared externally, as well as attribute 'org.gradle.plugin.api-version' with value '7.6.1' but:
          - Variant 'apiElements' capability org.springframework.boot:spring-boot-gradle-plugin:3.0.7 declares a library, packaged as a jar, and its dependencies declared externally:
              - Incompatible because this component declares an API of a component compatible with Java 17 and the consumer needed a runtime of a component compatible with Java 8
              - Other compatible attribute:
                  - Doesn't say anything about org.gradle.plugin.api-version (required '7.6.1')
          - Variant 'javadocElements' capability org.springframework.boot:spring-boot-gradle-plugin:3.0.7 declares a runtime of a component, and its dependencies declared externally:
              - Incompatible because this component declares documentation and the consumer needed a library
              - Other compatible attributes:
                  - Doesn't say anything about its target Java version (required compatibility with Java 8)
                  - Doesn't say anything about its elements (required them packaged as a jar)
                  - Doesn't say anything about org.gradle.plugin.api-version (required '7.6.1')
          - Variant 'mavenOptionalApiElements' capability org.springframework.boot:spring-boot-gradle-plugin-maven-optional:3.0.7 declares a library, packaged as a jar, and its dependencies declared externally:
              - Incompatible because this component declares an API of a component compatible with Java 17 and the consumer needed a runtime of a component compatible with Java 8
              - Other compatible attribute:
                  - Doesn't say anything about org.gradle.plugin.api-version (required '7.6.1')
          - Variant 'mavenOptionalRuntimeElements' capability org.springframework.boot:spring-boot-gradle-plugin-maven-optional:3.0.7 declares a runtime of a library, packaged as a jar, and its dependencies declared externally:
              - Incompatible because this component declares a component compatible with Java 17 and the consumer needed a component compatible with Java 8
              - Other compatible attribute:
                  - Doesn't say anything about org.gradle.plugin.api-version (required '7.6.1')
          - Variant 'runtimeElements' capability org.springframework.boot:spring-boot-gradle-plugin:3.0.7 declares a runtime of a library, packaged as a jar, and its dependencies declared externally:
              - Incompatible because this component declares a component compatible with Java 17 and the consumer needed a component compatible with Java 8
              - Other compatible attribute:
                  - Doesn't say anything about org.gradle.plugin.api-version (required '7.6.1')
          - Variant 'sourcesElements' capability org.springframework.boot:spring-boot-gradle-plugin:3.0.7 declares a runtime of a component, and its dependencies declared externally:
              - Incompatible because this component declares documentation and the consumer needed a library
              - Other compatible attributes:
                  - Doesn't say anything about its target Java version (required compatibility with Java 8)
                  - Doesn't say anything about its elements (required them packaged as a jar)
                  - Doesn't say anything about org.gradle.plugin.api-version (required '7.6.1')

* Try:
> Run with --stacktrace option to get the stack trace.
> Run with --info or --debug option to get more log output.
> Run with --scan to get full insights.

* Get more help at https://help.gradle.org

CONFIGURE FAILED in 7s

FAILURE: Build failed with an exception가 발생해서 에러 내용을 파악하다보니 "Doesn't say anything about its target Java version (required compatibility with Java 8)" 가 에러 가장 마지막 부분에 보였다.

 

에러 내용 상 Java 버전에 대해 불만이 있는 것으로 보이며, 이러한 버전 관련 에러는 build.gradle 파일의 기본 설정을 변경해서 해결 할 수 있었다.

 

프로젝트 생성 직후 순정 build.gradle 

plugins {
	id 'java'
	id 'war'
	id 'org.springframework.boot' version '3.0.7'
	id 'io.spring.dependency-management' version '1.1.0'
}

group = 'com.jsonm.dev.demo'
version = '0.0.1-SNAPSHOT'
sourceCompatibility = '17'

repositories {
	mavenCentral()
}

dependencies {
	implementation 'org.springframework.boot:spring-boot-starter-web'
	providedRuntime 'org.springframework.boot:spring-boot-starter-tomcat'
	testImplementation 'org.springframework.boot:spring-boot-starter-test'
}

tasks.named('test') {
	useJUnitPlatform()
}

 

 

Gradle Build 에러 원인과 해결 방법

Springboot 3.x 버전부터 Java 17이 최소 Java 버전이기 때문에 build.gradle 파일에서 sourceCompatibility가 17로 자동 생성되어 있었지만 위에서 처음 프로젝트 생성 할때 Java version을 8로 설정했기 때문에 에러가 난 것이다. 
 
하지만 Java 17은 쓰지 않을 생각이고 Java 8을 사용할 수 있는 환경으로 구성하기로 결정했다. 경험상 최신 버전은 늘 사용하기가 불안하고 사용 경험이 있거나 검증된 버전으로 선택하는 것이 조금 더 안전하다고 생각했기 때문이다. (기껏 자바 8을 깔아놨는데, 17로 바꾸는 게 귀찮아서 이기도 하다.)
 
Java 8 환경을 이용하기 위해 build.gradle의 plugins 안의 SpringBoot 버전을 2.7.4로 다운그레이드하였고, build.gradle 파일에서 sourceCompatibility도 1.8로 변경해 주면서 오류 해결!

plugins {
	id 'java'
	id 'war'
	id 'org.springframework.boot' version '2.7.4'
	id 'io.spring.dependency-management' version '1.0.14.RELEASE'
}

group = 'com.jsonm.dev.demo'
version = '0.0.1-SNAPSHOT'
sourceCompatibility = '1.8'

 

war 파일 설정
계속해서 build output을 war 로 만들기 위해 bootWar를 추가해준다.
이렇게 해 두면 빌드 성공 시 여기서 정한 파일명으로 war 파일을 만들어 준다.

bootWar {
    enabled = true
    archiveBaseName='jsonmdemo'
    archiveFileName='jsonmdemo.war'
    archiveVersion="0.0.0"
}

 
Gradle 의존성 추가

회사에서는 주로 Maven을 사용했었는데, Gradle을 통해 Dependency를 관리해보니 Maven보다 빠르고 편리한 것 같아서 귀찮지만 사용법을 최소한으로만 배워봤다. 
 
우선 Spring Security, MariaDB, JPA 등 유명한 아이들을 추가해 준다. 
thymeleaf의 경우는 back과 front를 완전히 분리시켜서 만들 예정이라 우선 주석처리 했고, 대신 jwt 토큰 인증 방식을 사용할 예정이라 관련 패키지를 설치했고, 전에 설치한 lombok 도 추가 해줬다.
 

dependencies {
	implementation 'org.springframework.boot:spring-boot-starter-security'
	implementation 'org.springframework.boot:spring-boot-starter-web'
	implementation 'org.springframework.boot:spring-boot-starter-data-jpa'
	//implementation 'org.springframework.boot:spring-boot-starter-thymeleaf'
	//implementation group: 'nz.net.ultraq.thymeleaf', name: 'thymeleaf-layout-dialect', version: '2.4.1'
	//implementation 'org.thymeleaf.extras:thymeleaf-extras-springsecurity5'
	implementation 'org.apache.commons:commons-lang3:3.12.0'
	implementation 'commons-io:commons-io:2.11.0'
	implementation 'io.jsonwebtoken:jjwt:0.9.1'
	implementation 'com.google.code.gson:gson:2.9.0'
	
	runtimeOnly 'org.mariadb.jdbc:mariadb-java-client'
	providedRuntime 'org.springframework.boot:spring-boot-starter-tomcat'
	testImplementation 'org.springframework.boot:spring-boot-starter-test'
	testImplementation 'org.springframework.security:spring-security-test'
	compileOnly 'org.projectlombok:lombok'
	annotationProcessor 'org.projectlombok:lombok'
}

 

수정 완료 된 build.gradle

plugins {
	id 'java'
	id 'war'
	id 'org.springframework.boot' version '2.7.4'
	id 'io.spring.dependency-management' version '1.0.14.RELEASE'
}

bootWar {
    enabled = true
    archiveBaseName='jsonmdemo'
    archiveFileName='jsonmdemo.war'
    archiveVersion="0.0.0"
}

group = 'com.jsonm.dev.demo'
version = '0.0.1-SNAPSHOT'
sourceCompatibility = '1.8'

repositories {
	mavenCentral()
}

dependencies {
	implementation 'org.springframework.boot:spring-boot-starter-security'
	implementation 'org.springframework.boot:spring-boot-starter-web'
	implementation 'org.springframework.boot:spring-boot-starter-data-jpa'
	//implementation 'org.springframework.boot:spring-boot-starter-thymeleaf'
	//implementation group: 'nz.net.ultraq.thymeleaf', name: 'thymeleaf-layout-dialect', version: '2.4.1'
	//implementation 'org.thymeleaf.extras:thymeleaf-extras-springsecurity5'
	implementation 'org.apache.commons:commons-lang3:3.12.0'
	implementation 'commons-io:commons-io:2.11.0'
	implementation 'io.jsonwebtoken:jjwt:0.9.1'
	implementation 'com.google.code.gson:gson:2.9.0'
	
	runtimeOnly 'org.mariadb.jdbc:mariadb-java-client'
	providedRuntime 'org.springframework.boot:spring-boot-starter-tomcat'
	testImplementation 'org.springframework.boot:spring-boot-starter-test'
	testImplementation 'org.springframework.security:spring-security-test'
	compileOnly 'org.projectlombok:lombok'
	annotationProcessor 'org.projectlombok:lombok'
}

tasks.named('test') {
	useJUnitPlatform()
}

 

Gradle Project Update

수정이 완료되었으면 파일 저장 후 gradle project refresh를 해준다.

 

프로젝트 명을 우클릭하면 [Grale] → [Refresh Gradle Project] 로 업데이트하면 된다.
평소에도 build.gradle 파일의 변경이 일어날 때마다 refresh 해주면 자동으로 Gradle Dependency가 업데이트가 된다.
 

이클립스 Springboot 프로젝트 Gradle Refresh 창

 
 
refresh를 하고 나니 아까 2개밖에 없던 폴더가 잔뜩 늘어나고 JavaSE-1.8 및 Dependency가 모두 추가된 것을 볼 수 있다.
그리고 결정적으로 에러가 발생하면 나오는 빨간색 x가 사라졌다. 
 
이제는 새로운 프로젝트를 시작할 수 있는 가장 기본적인 준비는 된 것이다.
 

이클립스 Springboot 프로젝트 생성 후 폴더 구조 모습

 
 
기본 폴더 구조를 보면 src/main 아래에 javaresources로 나뉘어 있고 앞으로 프로그램과 리소스들을 차근차근 추가해 나가면 된다.
 


 

 

 

2023.05.21 - [IT 개발] - [SpringBoot] 스프링부트 기초 #1 - Eclipse 개발 환경 구성

 

[SpringBoot] 스프링부트 기초 #1 - Eclipse 개발 환경 구성

Spring Framework가 가진 사상과 철학을 잘 이해하고 사용하는 Spring 전문가라 절대 말할 수는 없지만, Spring Boot를 이용해서 개발 요청이 들어오는 경우가 종종 있어서, 프레임워크에서 기본적으로 지

jsonm.tistory.com

 

2023.05.25 - [IT 개발] - [SpringBoot] 스프링부트 기초 #3 - 최초 접속 테스트

 

[SpringBoot] 스프링부트 기초 #3 - 최초 접속 테스트

Springboot 프로젝트 생성을 마쳤다면 가장 먼저 하고 싶은 일은 아마도 내가 만든 앱이 일단 접속이 되는지 확인하는 것일 것 같다. 브라우저에 localhost:8080을 쳐서 뭐라도 떠야 안심이 되지 않을까

jsonm.tistory.com

 

2023.05.30 - [IT 개발] - [SpringBoot] 스프링부트 기초 #4 - applicaion.yml 환경 분리

 

[SpringBoot] 스프링부트 기초 #4 - applicaion.yml 환경 분리

application.yml 파일 하나로 로컬, 개발 및 운영서버 각각의 환경 설정이 가능하다. 여기서는 단일 yml 파일과 Tomcat의 setenv.sh 파일을 이용해서 구성하는 방법을 사용했다. 공부차원에서 로컬에서만

jsonm.tistory.com

 

반응형