在 https://blog.youkuaiyun.com/zero__007/article/details/54914598 中介绍了生成可运行jar包的方式,第一种是把所有内容打入一个jar包,其实已经有这样的插件了—Shadow Plugin
,这个插件怎么用可以看 http://imperceptiblethoughts.com/shadow/ 。
来个例子:
buildscript {
repositories {
maven { url 'http://maven.aliyun.com/nexus/content/groups/public/' }
}
dependencies {
classpath "com.github.jengelman.gradle.plugins:shadow:2.0.4"
}
}
apply plugin: 'java'
apply plugin: "com.github.johnrengelman.shadow"
repositories {
mavenLocal()
maven { url 'http://maven.aliyun.com/nexus/content/groups/public/' }
maven { url 'https://repo.spring.io/libs-snapshot/' }
}
dependencies {
compile 'dom4j:dom4j:1.6.1'
compile group: 'org.mybatis', name: 'mybatis', version: '3.4.5'
compile 'javax.servlet:servlet-api:2.5'
}
//禁掉jar task
jar.enabled = false
shadowJar {
baseName = 'jarName'
//classifier是生成jar包的后缀
classifier = null
version = '1.0.0'
manifest {
attributes 'Main-Class': 'Test'
}
exclude 'no-overflow.css'
dependencies {
// 排除掉mybatis代码
exclude(dependency('org.mybatis:mybatis'))
}
}
assemble.dependsOn(shadowJar)
执行gradle build即可。
在某些场合,我们不需要依赖和src打在一个jar包,我们希望有个lib,然后我们的jar运行时,自动去找依赖jar。这样,就可以不用插件了:
task copyDependencies(type: Copy) {
from configurations.runtime
into 'build/libs/lib'
}
jar.dependsOn(copyDependencies)
jar {
manifest {
attributes "Implementation-Title": project.name
attributes "Implementation-Version": '1.0.0'
attributes 'Main-Class': 'Test'
}
if (!configurations.runtime.isEmpty()) {
manifest.attributes('Class-Path': '. lib/' + configurations.runtime.collect { it.name }.join(' lib/'))
}
}
原理就是在MANIFEST.MF
中加入了Class-Path
属性。运行时,jar包要和lib目录在同一级目录下,当然也可以根据需要修改。