Gradle构建java库

gradle init --type <name>其中name可选

  • java-application
  • java-library
  • scala-library
  • groovy-library
  • basic

build java-library

This guide walks you through the process of using Gradle’s Build Init plugin to produce a JVM library which is suitable for consumption by other JVM libraries and applications.

本指南引导您完成使用Gradle的Build Init插件生成适合其他JVM库和应用程序使用的JVM库的过程。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
mkdir demo-java-lib #创建项目目录
cd demo-java-lib
gradle init --type java-library #初始化构建为java-library
tree #查看生成的目录树
├── build.gradle
├── gradle
│   └── wrapper
│   ├── gradle-wrapper.jar
│   └── gradle-wrapper.properties
├── gradlew
├── gradlew.bat
├── settings.gradle
└── src
├── main #java资源为件
│   └── java
│   └── Library.java
└── test #java测试文件
└── java
└── LibraryTest.java

build.gradle解读

1
2
3
4
5
6
7
8
9
10
11
12
13
14
plugins {
// Java Library依赖插件
id 'java-library'
}
dependencies {
// 依赖该api
api 'org.apache.commons:commons-math3:3.6.1'
implementation 'com.google.guava:guava:23.0'
testImplementation 'junit:junit:4.12'
}
repositories {
// 仓库
jcenter()
}

执行./gradew build第一次构建会下载依赖jar包比较慢,下载到目录~/.gradle/wrapper/dists,编译完成后生成

  • build/reports/tests/test/index.html 测试报告
  • build/libs/building-java-libraries.jar 编译生成的jar

jar tf build/libs/building-java-libraries.jar命令查看jar包内容,其中-f指定jar文件名,-t列出包的内容

修改build.gradle文件在文件里添加版本好version = '0.1.0',结果会修改打包的名称为build/libs/demo-java-lib-0.1.0.jar

修改build.gradle文件在文件里添加jar task任务

1
2
3
4
5
6
jar {
manifest {
attributes('Implementation-Title': project.name,
'Implementation-Version': project.version)
}
}

会修改build/libs/building-java-libraries-0.1.0.jar/META-INF/MANIFEST.MFjar包文件的内容为

1
2
3
Manifest-Version: 1.0
Implementation-Title: demo-java-lib
Implementation-Version: 0.1.0

java-library内置支持javadoc,执行./gradlew javadoc会生成/build/docs/javadoc/index.html文档

build java-application

java项目和library项目一样,只是多了tasks任务 run