Gradle #4 - build.gradle 파일의 역할
Gradle 시리즈
글 요약
-
build.gradle
파일을 통해, 프로젝트 빌드 옵션을 설정할 수 있다. -
build.gradle
의 구성요소는 크게plugins
,repositories
,dependencies
,test
가 있다. -
plugin
은 Gradle에서 미리 만든build.gradle
파일을 불러오는 데 사용한다. -
repositories
는 프로젝트를 빌드 할 외부 자료 저장소를 설정할 때 사용한다. -
dependencies
는 프로젝트를 빌드 할 때 사용하는 외부 자료 목록이 존재한다. -
test
는 프로젝트를 테스트 할 때 사용 할 JUnit5 등 테스트 프레임워크를 설정할 수 있다.
🔎 gradle.build 파일
gradle.build
는 gradle을 이용해 프로젝트를 빌드할 때 사용하는 스크립트 파일입니다. 이전 포스트에서 생성한 프로젝트 내 subProject인 lib/build.gradle
파일을 살펴보겠습니다.
🩻 build.gradle 구조
build.gradle 파일은 보통 plugins, repositories, dependencies, test로 구성되어 있습니다 아래의 파일 내용을 바탕으로 설명드리겠습니다.
/*
* This file was generated by the Gradle 'init' task.
*
* This generated file contains a sample Java library project to get you started.
* For more details on building Java & JVM projects, please refer to https://docs.gradle.org/8.4/userguide/building_java_projects.html in the Gradle documentation.
*/
plugins {
// Apply the java-library plugin for API and implementation separation.
id 'java-library'
}
repositories {
// Use Maven Central for resolving dependencies.
mavenCentral()
}
dependencies {
// Use JUnit Jupiter for testing.
testImplementation 'org.junit.jupiter:junit-jupiter:5.9.3'
testRuntimeOnly 'org.junit.platform:junit-platform-launcher'
// This dependency is exported to consumers, that is to say found on their compile classpath.
api 'org.apache.commons:commons-math3:3.6.1'
// This dependency is used internally, and not exposed to consumers on their own compile classpath.
implementation 'com.google.guava:guava:32.1.1-jre'
}
// Apply a specific Java toolchain to ease working on different environments.
java {
toolchain {
languageVersion = JavaLanguageVersion.of(17)
}
}
tasks.named('test') {
// Use JUnit Platform for unit tests.
useJUnitPlatform()
}
🔌 plugins
plugins는 이미 정의된 task들을 가져다 쓰기 위해 사용됩니다. 가져다 쓸 미리 정의된 plugin은 id
를 이용하여 추가할 수 있습니다.
예제 에서는 java-library
플러그인을 사용하고 있으며 id
값만 존재하기 때문에 Gradle 에서 제공하는 core plugin을 사용한다는 의미로 볼 수 있습니다.
plugins {
// Apply the java-library plugin for API and implementation separation.
id 'java-library'
}
Gradle이 제공하는 core plugin은 plugin reference에서 찾아 보실 수 있습니다.
🔄 plugin 변경 해보기
플러그인을 아래와 같이 'application'으로 변경한 후, ./gradlew tasks
를 입력하면 java-library 에서 지원하는 task 목록과 달리, Application tasks 가 추가가 되었음을 확인할 수 있습니다.
Application tasks
-----------------
run - Runs this project as a JVM application
(...생략...)
✅ Application 플러그인 적용해보기
1️⃣ gradle.build 파일 수정
이전 글에서 생성한 subProject인 moosong
을 실행 가능한 application으로 변경해봅시다.
application 플러그인을 사용하기 위해 application id를 추가한 후 실행 할 class를 지정해주기 위해 application 블럭을 추가합니다. mainClass
에는 gradle.example.Main
을 추가합니다.
plugins {
id 'java-libaray'
id 'application'
}
application {
mainClass = 'gradle.example.Main'
}
2️⃣ 프로젝트 Main.java 파일 추가
mainClass
와 맞추기 위해 src/main/java/gradle/example
경로에 Main.java
를 아래와 같이 추가합니다.
moosong/src/main/java/gradle/example/Main.java | |
---|---|
3️⃣ 프로젝트 실행
./gradlew :moosong:run을 입력하게 되면 moosong subProject내의 Main.java 파일 안에 "Hello World!"가 출력되는 것을 확인할 수 있습니다.
fromitive@dev:~/practice/gradle-example$ ./gradlew :moosong:run
> Task :moosong:run
Hello World!
BUILD SUCCESSFUL in 6s
2 actionable tasks: 2 executed
🗃️ repositories
repositories의 명칭은 GitHub에서 말하는 repository와 같습니다. 즉, 자바 외부 자료를 참조하기 위한 저장소. 라고 생각하시면 됩니다. 현재 아래와 같이 MavenCentral() 저장소를 사용하고 있으며, 이는 maven 저장소에 등록되어 있는 외부 자료를 참조합니다.
repositories {
// Use Maven Central for resolving dependencies.
mavenCentral()
}
😺 GitHub 자료를 참조하기 위한 구문
GitHub에 등록된 repository를 참조할 수도 있습니다. "jitpack.io" 문구를 추가하면, GitHub repository를 참조하여, 해당 repository를 사용 가능합니다.
repositories {
mavenCentral()
maven { url 'https://jitpack.io' }
}
⛓️ dependencies
빌드할 프로젝트의 의존성 자료 목록이 있습니다. 의존성 자료는 프로젝트를 빌드할 때, 필요한 자바 파일들이라고 생각하면 됩니다. 이 안에 등록된 자료들을 repositories
내에 mavenCentral
및 jitpack.io
와 같은 저장소를 참고하여 다운 받습니다.
python으로 생각한다면 pip install -r requirements.txt
같은 역할을 한다고 하면 됩니다.
파일을 자세히 살펴보면 testImplementation
, testRuntimeOnly
, api
, implementation
설정값 이 있습니다.
dependencies {
// Use JUnit Jupiter for testing.
testImplementation 'org.junit.jupiter:junit-jupiter:5.9.3'
testRuntimeOnly 'org.junit.platform:junit-platform-launcher'
// This dependency is exported to consumers, that is to say found on their compile classpath.
api 'org.apache.commons:commons-math3:3.6.1'
// This dependency is used internally, and not exposed to consumers on their own compile classpath.
implementation 'com.google.guava:guava:32.1.1-jre'
}
기본적으로 생성되는 프로젝트의 dependencies의 각 설정 값에 대한 설명은 아래와 같습니다. implementation
과 api
이 같은기능을 하면서 접근 제어의 차이가 있습니다.
설정 값 | 설명 |
---|---|
testImplementation | test 디렉터리에 있는 테스트들을 컴파일 할 때 필요한 자료들만 받습니다. |
implementation | 테스트와 메인에 대한 구분 없이 자료를 받습니다. 설정되어 있는 자료에 대한 내용만 접근 가능합니다. |
api | implementation 과 다르게 외부 자료가 참조한 자료들도 직접 참조할 수 있습니다. 예로 들어 A라는 외부 자료가 B에 의존하고 있다면, api "A"를 통해 B라는 자료도 직접 접근이 가능합니다. |
testRuntimeOnly | ./gradlew test 할 때 만 해당 외부 자료를 참조합니다. |
설정 값의 대한 설명은 아래와 같습니다. 설정 값은 아래와 같이 구성되어 있습니다.1
예로 들어 implementation 'com.google.guava:guava:32.1.1-jre'
그룹명이 com.google.guava
이고, 자료 명은 guava
입니다. 마지막으로 버전은 32.1.1-jre
를 사용한다고 해석됩니다. 실제로 mavenCentral 저장소에 해당 자료가 있는 것을 확인할 수 있습니다.
😺 GitHub에 있는 repository를 의존성에 추가하는 방법
GtiHub에 저장되어 있는 자료를 추가하려면 아래와 같이 입력하면 추가할 수 있습니다. 단, repositories
에 jitpack.io
를 추가해야 합니다.
repositories {
mavenCentral()
maven { url 'https://jitpack.io' }
}
dependencies {
implementation 'com.github.[userid]:[repository name]:release'
}
🔎 프로젝트의 의존성을 확인할 수 있는 방법
프로젝트의 의존성을 확인하기 위해서는 ./gradlew dependencies를 통해 확인이 가능합니다.
다음은 moosong subProject의 의존성을 보여줍니다.
각 task 수행 시 사용되는 의존성까지 알려주기 때문에 의존성을 바로 확인할 수 있습니다.
fromitive@dev:~/practice/gradle-example$ ./gradlew :moosong:dependencies
> Task :moosong:dependencies
------------------------------------------------------------
Project ':moosong'
------------------------------------------------------------
annotationProcessor - Annotation processors and their dependencies for source set 'main'.
No dependencies
api - API dependencies for the 'main' feature. (n)
\--- org.apache.commons:commons-math3:3.6.1 (n)
(..생략..)
implementation - Implementation dependencies for the 'main' feature. (n)
\--- com.google.guava:guava:32.1.1-jre (n)
(..생략..)
runtimeClasspath - Runtime classpath of source set 'main'.
+--- org.apache.commons:commons-math3:3.6.1
\--- com.google.guava:guava:32.1.1-jre
(..생략..)
🧪 test
test
설정 부분은 test 하기 위해 사용 할 test 프레임워크의 종류를 지정하는 부분입니다. 사용할 수 있는 설정 값은 gradle init
할 때, 나온 test 프레임워크인 JUnit-4
, TestNG
, JUnit Platform-based
입니다.
아래처럼 task.test를 이용하여 작성할 수도 있지만 test
블럭을 이용하여 설정할 수도 있습니다
✔ JUnit Platform?
JUnit Platform
테스트를 사용한다는 의미는 JUnit5를 사용한다는 의미와 같다고 합니다. JUnit은 아래와 같이 3개의 구성 요소르 이루어져 있습니다.
따라서 JUnit5
을 온전히 사용하기 위해 Gradle에서는 init 시 아래와 같은 dependencies를 추가하는 것으로 보입니다. 프로그램 실행 시 JUnit Platform을 이용하여, JUnit Jupiter 기반으로 작성된 테스트를 실행합니다.
dependencies {
// Use JUnit Jupiter for testing.
testImplementation 'org.junit.jupiter:junit-jupiter:5.9.3'
testRuntimeOnly 'org.junit.platform:junit-platform-launcher'
// (..생략..)
}
참고 자료
참고 자료
- Building Java Projects with Gradle - Spring 공식 문서
- Using Gradle Plugins - Gradle 공식 문서
- plugin reference(Gradle core plugin 종류) - Gradle 공식 문서
- Declaring repositories(maven 저장소 URL) - Gradle 공식 문서
- Dependency management(지원 가능한 설정 값들) - Gradle 공식 문서
- API and implementation sepration(api 와 implementation의 차이) - Gradle 공식 문서
- implementation vs api(api 와 implementation의 차이) - StackOverflow
- DependencyHandler(dependencies 설정 값 작성 법) - Gradle 공식 문서
- Test Class(지원하는 Test 프레임워크 목록) - Gradle 공식 문서
- Using JUnit 5(JUnit5 구성 요소) - Gradle 공식 문서
-
설정 값에대한 표기법은 DependencyHandler - Gradle 공식 문서에서 찾을 수 있었습니다. 이 안에 다양한 표기법이 있으니, 자세히 알고 싶으시다면 해당 사이트에 접속하셔서 확인하셔도 됩니다. ↩