Project一:
Java的默认工程配置情况;
build.gradle代码:
apply plugin: 'java'
Java 代码目录所在位置:src/main/java/*.java
项目的目录结构:
2014/02/04 08:38 20 build.gradle
2014/02/04 08:38 <DIR> src
1 个文件 20 字节
3 个目录 180,441,735,168 可用字节
分析:在默认情况下,Java的所在位置为:src/main/Java/ ,所以build.gradle仅引用了一个java插件,即可编译Java项目,编译结果如下:
>gradle build
:compileJava
:processResources UP-TO-DATE
:classes
:jar
:assemble
:compileTestJava UP-TO-DATE
:processTestResources UP-TO-DATE
:testClasses UP-TO-DATE
:test UP-TO-DATE
:check UP-TO-DATE
:build
BUILD SUCCESSFUL
Total time: 5.554 secs
Project二:
大多数情况下,Java都有自己的一套习惯配置,比如将Java代码放入src/目录下,而不是src/main/java目录!那如何配置呢?
build.gradle 文件:
apply plugin: 'java'
version = 0.1
sourceCompatibility = 1.6
sourceSets {
main {
java {
srcDirs = ['src']
}
}
}
buildDir = 'out'
jar {
manifest {
attributes 'Main-Class': 'com.manning.gia.todo.ToDoApp'
}
}
而Java代码的位置位于:src/
分析:以上build.gradle文件,引用Java插件后,调用了Java插件相应的Properties和Methods以及 Script blocks。
首先,Java插件的Properties之一:
sourceCompatibility | The source compatibility used for compiling Java sources. |
---|
其次:Java插件的Methods有:‘
Method | Description |
---|---|
manifest() | Creates a new instance of a Manifest. |
manifest(closure) | Creates and configures a new instance of a Manifest. The given closure configures the new manifest instance before it is returned. |
上面代码
jar {
就是引用该方法
manifest {
attributes 'Main-Class': 'com.manning.gia.todo.ToDoApp'
}
}
再次:引用Script blocks:Java插件的脚本块有:
Block | Description |
---|---|
reporting | Configures the ReportingExtension added by the java plugin. |
sourceSets | Configures the source sets of this project. |
脚本块的示例有:
apply plugin: 'java'
sourceSets {
main {
java {
exclude 'some/unwanted/package/**'
}
}
}
Project 三
使用zip进行压缩文件夹
代码位置在../tutorial/zipWithCustomName/
version = 1.0
task myZip(type: Zip) {
from 'somedir'
baseName = 'sss'
}
println myZip.archiveName
其实,在原有代码中还有apply plugin: ‘java’这句话,但是由于运行时和task中并没有关于Java的使用。执行该脚本后,会 生成一个build/distributions/sss-1.0.zip的文件,即生成一个压缩文件!
baseName控制着压缩文件的名字,version控制着该版本号!
Project 四
编译出错时抛异常
代码位置在../tutorial/stopException/
task compile << {
println 'We are doing the compile.'
}
compile.doFirst {
// Here you would put arbitrary conditions in real life.
// But this is used in an integration test so we want defined behavior.
if (true) { throw new StopExecutionException() }
}
task myTask(dependsOn: 'compile') << {
println 'I am not affected'
}
分析:在执行task名为compile时,抛出了一个异常StopExecutionException,导致compile停止执行,所以没有执行compile的打印语句!但是该异常是代码中主动抛出的,并没有影响这个项目的编译!!