Gradle学习笔记・02・使用Gradle编译Java项目
Java代码目录结构默认遵循maven的规范:
$ tree
.
├── build.gradle
└── src
└── main
└── java
└── org
└── weli
└── HelloWorld.java
5 directories, 2 files
「HelloWorld.java」代码的内容:
package org.weli;
public class HelloWorld {
public static void main(String args[]) {
System.out.println("Hello, world!");
}
}
「build.gradle」的内容:
apply plugin: 'java'
「java plugin」会自动引入一些默认task支持maven目录规范。使用下面的命令编译项目:
$ 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: 3.639 secs
编译完成后代码目录内容如下:
$ tree
.
├── build
│ ├── classes
│ │ └── main
│ │ └── org
│ │ └── weli
│ │ └── HelloWorld.class
│ ├── dependency-cache
│ ├── libs
│ │ └── 02.jar
│ └── tmp
│ ├── compileJava
│ └── jar
│ └── MANIFEST.MF
├── build.gradle
└── src
└── main
└── java
└── org
└── weli
└── HelloWorld.java
15 directories, 5 files
执行编译后的代码:
$ java -cp build/classes/main/ org.weli.HelloWorld
Hello, world!
如果想要gradle自动创建上面的java项目结构,可以先创建一个新的项目:
$ mkdir sample-gradle-project
然后进到这个项目的目录当中:
$ cd sample-gradle-project/
然后在空的项目目录里使用下面的命令:
$ gradle init --type java-library
Starting a new Gradle Daemon for this build (subsequent builds will be faster).
:wrapper
:init
BUILD SUCCESSFUL
Total time: 9.457 secs
这样就生成了gradle的java项目结构及文件:
$ tree
.
├── build.gradle
├── gradle
│ └── wrapper
│ ├── gradle-wrapper.jar
│ └── gradle-wrapper.properties
├── gradlew
├── gradlew.bat
├── settings.gradle
└── src
├── main
│ └── java
│ └── Library.java
└── test
└── java
└── LibraryTest.java
7 directories, 8 files
以上的方法来自于「Create Java project structure automatically」这篇文章1的介绍。