Gradle生成可執行jar包(二)
阿新 • • 發佈:2019-01-01
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目錄在同一級目錄下,當然也可以根據需要修改。