This document explains how to use gradle in Java project. It contains a real sample build file using Spring MVC project which is using education example in OSC.
2. Overview
Gradle은 매우 유연한 범용의 빌드 툴로써 다음과 같은 특징을 가진다.
Groovy를 기반으로 한 확장 가능한 DSL(Domain Specific Language)이다.
빌드 로직들을 손쉽게 조합하여 재사용 할 수 있다.
간단한 Single Project 부터 복잡한 Multi Project 까지 뛰어난 확장성을 제공함으로써 생산
성을 향상시킨다.
Maven, Ivy, Jars 또는 로컬 파일시스템의 디렉토리 등 다양한 방법으로 의존성 관리를 할
수 있다.
기존 어떠한 구조의 프로젝트라도 Gradle로의 Migration을 쉽게 할 수 있다.
기존에 작성된 Ant Task를 Gradle에서 직접 호출할 수 있다.
Groovy 기반의 빌드 스크립트를 사용함으로써 third party libraries를 포함시키고 커스터
마이즈 할 수 있다.
Gradle Wrapper를 사용하여 Gradle이 설치되지 않은 환경에서도 빌드가 가능하다.
2
- Internal Use Only -
3. Installing Gradle
Gradle은 모든 OS에 대해 다음과 같은 순서로 쉽게 설치할 수 있다.
http://www.gradle.org/downloads 에 접속하여 Current Stable Release를 다운로드 한다.
다운로드 파일을 원하는 디렉토리에 압축 해제한다.
GRADLE_HOME 환경변수를 압축 해제한 디렉토리로 정의한다.
PATH 환경변수에 $GRADLE_HOME/bin을 추가한다.
$ wget http://services.gradle.org/distributions/gradle-1.10-all.zip
…
Connecting to downloads.gradle.org|54.239.186.240|:80... connected.
HTTP request sent, awaiting response... 200 OK
Length: 54965002 (52M) [application/zip]
Saving to: ‘gradle-1.10-all.zip’
100%[==================================================>] 54,965,002 11.1MB/s in 4.7s
2014-01-22 14:52:04 (11.0 MB/s) - ‘gradle-1.10-all.zip’ saved [54965002/54965002]
$ sudo unzip -q gradle-1.10-bin.zip -d /usr/local/
$ echo "export GRADLE_HOME=/usr/local/gradle-1.10" >> .bash_profile
$ echo "export PATH=$PATH:$GRADLE_HOME/bin" >> .bash_profile
3
- Internal Use Only -
4. The Gradle Command Line
명령창에서 gradle [option...] [task...]를 입력하여 Gradle build를 수행할 수 있으며,
대표적인 option 및 Help task는 다음과 같다.
-?, -h, --help : help message 출력
-q : 로그 출력 안함
-x, --exclude-task : 특정 task는 실행하지 않음
--continue : 빌드 실패 시 즉시 종료하지 않고, 독립적인 태스크들은 모두 수행
-d, --debug : stacktrace를 포함한 debug 정보 출력
-i, --info : Log Level을 INFO로 변경
-b, --build-file : build.gradle이 아닌 다른 빌드 파일을 선택하여 실행
-D, --system-prop : JVM의 System Property를 설정
--gui : Gradle GUI를 실행
projects : sub-project 목록을 표시
properties : properties 목록을 표시
tasks : 빌드 스크립트의 실행 가능한 모든 task 목록을 표시
4
- Internal Use Only -
5. Build Script Basics (1 / 6)
build.gradle는 project와 각각의 task들을 정의한 파일로 빌드 스크립트라 칭한다.
Gradle build는 하나 이상의 project로 구성된다.
각 project는 하나 이상의 task로 구성되며, task는 Ant의 target과 유사하다.
gradle 명령 실행 시 현재 디렉토리에서 build.gradle 파일을 탐색하고 빌드 스크립트에
정의한 내용으로 빌드를 수행한다.
Hello World
build.gradle 파일을 다음과 같이 작성한다. (신규 디렉토리 생성 및 디렉토리 변경 필요)
task hello {
doLast {
println 'Hello world!'
}
}
명령창에서 gradle -q hello 를 실행하여 결과를 확인한다.
$ gradle -q hello
Hello world!
5
- Internal Use Only -
7. Build Script Basics (3 / 6)
Task dependencies
task 간의 의존관계를 선언할 수 있다.
build.gradle
task hello << {
println 'Hello world!'
}
task intro(dependsOn: hello) << {
println "I'm Gradle"
}
Output of gradle -q intro
$ gradle -q intro
Hello world!
I'm Gradle
* Lazy dependsOn : dependsOn이 선언되는 시점에 해당 task가 정의되어 있지 않아도 무관
하며, 이는 multi-project build 시 중요한 요소가 된다.
7
- Internal Use Only -
8. Build Script Basics (4 / 6)
Dynamic tasks
Groovy를 이용하여 task를 정의하는 것 뿐만 아니라 동적으로 task를 생성할 수도 있다.
build.gradle
4.times { counter ->
task "task$counter" << {
println "I'm task number $counter"
}
}
task0.dedepndsOn task2, task3
Output of gradle -q task0
$ gradle -q task0
I'm task number 2
I'm task number 3
I'm task number 0
8
- Internal Use Only -
9. Build Script Basics (5 / 6)
Extra task properties
task에 사용자 정의 properties를 추가할 수 있으며, task property와 같이 읽거나 수정할
수 있다.
build.gradle
task myTask {
ext.myProperty = "myValue"
}
task printTaskProperties << {
println myTask.myProperty
}
Output of gradle -q printTaskProperties
$ gradle -q printTaskProperties
myValue
9
- Internal Use Only -
10. Build Script Basics (6 / 6)
Default tasks
하나 이상의 default task를 지정할 수 있다.
build.gradle
defaultTasks 'clean', 'run'
task clean << {
println 'Default Cleaning!'
}
task run << {
println 'Default Running!'
}
task other << {
println "I'm not a default task!"
}
Output of gradle -q
$ gradle -q
Default Cleaning!
Default Running!
10
- Internal Use Only -
11. Gradle Plugins(1 / 2)
Gradle은 Plugin 형태의 자동화 기능을 적용 가능하도록 지원하며, 자체 제공하는
Standard plugins, Third party plugins 뿐만 아니라 사용자가 직접 구현한 Custom
plugins도 적용할 수 있다.
Plugin으로 다음과 같은 작업을 수행할 수 있다.
compile, test 같은 task를 project에 추가할 수 있다.
적합한 기본값으로 태스크를 미리 설정할 수 있다.
project에 의존성을 설정할 수 있다.
확장을 통해 기존 타입에 새로운 property와 method를 추가할 수 있다.
Standard plugins
Language plugins : java, groovy, scala, antlr, assembler, c, cpp, cpp-exe, cpp-lib
Integration plugins : application, ear, jetty, maven, osgi, war 등
Software development plugins : eclipse, eclipse-wtp, idea, checkstyle, pmd 등
Base plugins : base, java-base, groovy-base, scala-base, reporting-base
11
- Internal Use Only -
12. Gradle Plugins(2 / 2)
Third-party plugins
http://wiki.gradle.org/display/GRADLE/Plugins 에서 다양한 third-party plugins 조회 가능
(2014.01.22 현재 87 가지의 third-party plugins이 존재).
Writing custom plugins
사용자가 직접 구현한 plugin을 의미하며, Groovy 뿐만 아니라 Java, Scala 등의 다양한
언어로 구현할 수 있다.
Plugin은 빌드 스크립트 내에 구현, 프로젝트 내의 특정 경로
(rootProjectDir/buildSrc/src/main/groovy)에 구현, 별도의 프로젝트로 구성하여 구현하는
세 가지 방법이 있다.
build.gradle
apply plugin: GreetingPlugin
class GreetingPlugin implements Plugin<Project> {
void apply(Project project) {
project.task('hello') << {
println "Hello from the GreetingPlugin"
}
}
}
12
- Internal Use Only -
13. Installing Eclipse Plugins
Eclipse Marketplace에서 gradle로 검색하여 다음 두 개의 plugin을 설치한다.
Minimalist Gradle Editor : *.gradle 파일 편집기
Gradle Integration for Eclipse : Gradle 프로젝트 생성 및 Gradle Build 기능 제공
Gradle Integration for Eclipse를 이용한 Gradle 빌드 시 Plugin 자체 wrapper를
이용하며 현재 release 되고 있는 버전과 많은 차이가 날 수 있다.
Eclipse의 Preferences 창에서 Gradle 메뉴의 Gradle Distribution 을 변경한다.
13
- Internal Use Only -
14. Building Java Web Application with Gradle(1 / 12)
Create project root directory
Eclipse의 workspace에 프로젝트 디렉토리를 생성 후 디렉토리를 이동한다.
$ cd /eclipse/workspace
$ mkdir gradle_sample
$ cd gradle_sample
build.gradle 파일을 다음과 같이 작성한다.
apply plugin: 'java'
apply plugin: 'war'
apply plugin: 'eclipse'
apply plugin: 'eclipse-wtp'
sourceCompatibility = 1.7
version = '1.0’
repositories {
// Maven 기본 저장소 사용
mavenCentral()
}
14
- Internal Use Only -
15. Building Java Web Application with Gradle(2 / 12)
project.ext {
// 의존성 설정에 사용할 프로퍼티
springVersion = '3.2.6.RELEASE'
slf4jVersion = '1.7.5'
}
sourceSets {
main {
// default 값은 build/classes/main, build/resources/main
output.classesDir = 'build/classes'
output.resourcesDir = 'build/classes'
}
test {
// default 값은 build/classes/test, build/resources/test
output.classesDir = 'build/test-classes'
output.resourcesDir = 'build/test-classes'
}
}
// JAVA 컴파일시 인코딩 설정
[compileJava, compileTestJava]*.options*.encoding = 'UTF-8'
15
- Internal Use Only -
16. Building Java Web Application with Gradle(3 / 12)
// 의존성 설정
dependencies {
compile "org.springframework:spring-aop:$springVersion",
"org.springframework:spring-beans:$springVersion",
"org.springframework:spring-context:$springVersion",
"org.springframework:spring-core:$springVersion",
"org.springframework:spring-web:$springVersion",
"org.springframework:spring-webmvc:$springVersion",
"org.springframework:spring-jdbc:$springVersion",
"org.springframework:spring-orm:$springVersion",
"org.springframework:spring-tx:$springVersion",
"org.springframework:spring-oxm:$springVersion”,
"org.mybatis:mybatis:3.2.3", "org.mybatis:mybatis-spring:1.2.1",
"javax.validation:validation-api:1.0.0.GA", "org.hibernate:hibernate-validator:4.3.0.Final",
"org.aspectj:aspectjweaver:1.7.4", "org.aspectj:aspectjrt:1.7.4",
"commons-lang:commons-lang:2.6", "commons-io:commons-io:2.4",
"commons-fileupload:commons-fileupload:1.3", "javax.ws.rs:jsr311-api:1.1.1",
"javax.servlet:jstl:1.2", "taglibs:standard:1.1.2", "org.slf4j:slf4j-api:$slf4jVersion",
"org.slf4j:jcl-over-slf4j:$slf4jVersion", "org.slf4j:slf4j-log4j12:$slf4jVersion",
"hsqldb:hsqldb:1.8.0.10", "org.codehaus.jackson:jackson-core-asl:1.9.8",
"org.codehaus.jackson:jackson-mapper-asl:1.9.8”
16
- Internal Use Only -
17. Building Java Web Application with Gradle(4 / 12)
providedCompile
testCompile
"javax.servlet:javax.servlet-api:3.0.1"
"org.springframework:spring-test:$springVersion”, "junit:junit:4.+”,
"com.sun.jersey:jersey-core:1.12", "com.sun.jersey:jersey-client:1.12”,
"com.jayway.jsonpath:json-path-assert:0.8.1"
}
// 모든 의존성에서 commons-logging는 제외
[configurations.runtime, configurations.default]*.exclude(module: 'commons-logging')
// TEST 설정
test {
jvmArgs = ['-ea', '-Xmx256m']
logging.captureStandardOutput(LogLevel.INFO)
reports.html.enabled = true // getReports().getHtml().setEnabled(true)
}
// src/main/java에 위치한 non java 파일을 output 디렉토리로 복사
processResources {
from('src/main/java') {
exclude '**/*.java'
}
17
- Internal Use Only -
18. Building Java Web Application with Gradle(5 / 12)
into 'build/classes'
includeEmptyDirs = true
}
// src/test/java에 위치한 non java 파일을 output 디렉토리로 복사
processTestResources {
from('src/test/java') {
exclude '**/*.java'
}
into 'build/test-classes'
includeEmptyDirs = true
}
// 프로젝트 초기화
// 1. java source directory 생성 : src/main/java, src/test/java
// 2. resource directory 생성 : src/main/resource, src/test/resource
// 3. web source directory 생성 : src/main/webapp, src/main/webapp/WEB-INF
task initProject(description: 'initialize project') << {
def createDir = {
println "create source directory: $it”
18
- Internal Use Only -
20. Building Java Web Application with Gradle(7 / 12)
wtp {
component {
// 원하는 contextPath 지정. 단, 빈 컨텍스트패스는 '/' 로 지정
contextPath = project.name
}
facet {
// Servlet Spec Version 지정
facet name: 'jst.web', version: '3.0'
// Java Version 지정, 1.7
facet name: 'jst.java', version: '1.7'
// Javascript 지정, 1.0
facet name: 'wst.jsdt.web', version: '1.0'
}
}
}
20
- Internal Use Only -
21. Building Java Web Application with Gradle(8 / 12)
Source directories 생성
gradle -q initProject를 실행하여 프로젝트 하위의 서브 디렉토리들을 생성한다.
$ gradle -q initProject
create source directory: /eclipse/workspace/gradle_sample/src/main/java
create source directory: /eclipse/workspace/gradle_sample/src/test/java
create source directory: /eclipse/workspace/gradle_sample/src/main/resources
create source directory: /eclipse/workspace/gradle_sample/src/test/resources
create source directory: /eclipse/workspace/gradle_sample/src/main/webapp
create source directory: /eclipse/workspace/gradle_sample/src/main/webapp/WEB-INF
Eclipse 관련 파일 생성
gradle -q eclipse를 실행하여 .project, .classpath 등 eclipse 관련 파일을 생성한다.
$ ls -a
.
..
.gradle
build.gradle src
$ gradle -q eclipse
$ ls -a
.
..
.classpath .gradle
.project
.settings
build.gradle src
21
- Internal Use Only -
22. Building Java Web Application with Gradle(9 / 12)
Import Project
File > Import > Gradle > Gradle Project를 선택한다.
생성한 프로젝트 디렉토리(/eclipse/workspace/gradle_sample)를 선택한다.
22
- Internal Use Only -
23. Building Java Web Application with Gradle(10 / 12)
Application 구현
https://github.com/OpenSourceConsulting/gradle_sample.git 참조
Run Gradle Build
실행하고자 하는 task들을 선택 후 실행한다. (eg. :clean, :test, :war)
23
- Internal Use Only -
24. Building Java Web Application with Gradle(11 / 12)
Test task
test task를 수행하면 build/test-results 디렉토리에 테스트 수행 결과가 저장되며,
build/reports/test 디렉토리에 레포트 파일이 생성된다.
24
- Internal Use Only -
25. Building Java Web Application with Gradle(12 / 12)
War task
war task를 실행하면 build/libs 디렉토리에 패키징 된 war 파일이 생성된다.
Clean task
clean task를 실행하면 build 디렉토리를 삭제한다.
25
- Internal Use Only -