Gradle, shadowJar: use relocate inside task

2019-07-31 08:11发布

I have the following task:

task myJar(type: Jar) {
    archiveName = 'myJar.jar'
    includeEmptyDirs = false
    destinationDir = rootProject.libsDir
    dependsOn compileJava

    manifest.attributes('Class-Path': '../lib/commons-lang-2.5.jar')

    into '/', {
        from compileJava.destinationDir
        include 'com/myCompany/project/util/order/**',
                'com/myCompany/project/event/**',
    }
}

and I would like to relocate all classes from com/myCompany/project/event/** to com/myCompany/relocated/project/event/** (so that some apps using my jar and having com.myCompany.project.event package defined will avoid any possible conflicts)

I discovered that it can be done using shadow plugin and I tried to add

relocate 'com.myCompany.project.event.', 'com.myCompany.relocated.project.event.'

under this task but it doesn't seem to work. Does anybody know where I should add this line?

1条回答
叼着烟拽天下
2楼-- · 2019-07-31 08:40

You can achieve this by adding below plugin to your build.gradle

apply plugin: 'com.github.johnrengelman.shadow'

After adding this plugin add below code to your build.gradle file

shadowJar {
    relocate 'com.myCompany.project.event', 'com.myCompany.relocated.project.event'
}

After adding this, to ensure your ShadowJar task runs before build, add this line at the end

assemble.dependsOn shadowJar

This will ensure that shadow jar task is triggered before assemble/build task during gradle build.

On doing the Gradle build, you should see all your packages and their corresponding dependencies relocated from 'com.myCompany.project.event' to 'com.myCompany.relocated.project.event'.

For more info you can refer to ShadowJarUserGuide

查看更多
登录 后发表回答