【问题标题】:Gradle: How to add a custom task after compilation but before packaging files into a Jar?Gradle:如何在编译后但在将文件打包到 Jar 之前添加自定义任务?
【发布时间】:2014-07-22 23:14:41
【问题描述】:

我的 build.gradle 目前是:

project(':rss-middletier') {
    apply plugin: 'java'

    dependencies {
        compile project(':rss-core')
        compile 'asm:asm-all:3.2'
        compile 'com.sun.jersey:jersey-server:1.9.1'
        compile group: 'org.javalite', name: 'activejdbc', version: '1.4.9'
    }

    jar {
        from(configurations.compile.collect { it.isDirectory() ? it : zipTree(it) }) {
            exclude "META-INF/*.SF"
            exclude "META-INF/*.DSA"
            exclude "META-INF/*.RSA"
        }
        manifest { attributes 'Main-Class': 
'com.netflix.recipes.rss.server.MiddleTierServer' }
    }
}

但不是直接将这些编译的类打包到一个 jar 中,我想首先通过运行以下任务来检测它们:

task instrument(dependsOn: 'build', type: JavaExec) {
    main = 'org.javalite.instrumentation.Main'
    classpath = buildscript.configurations.classpath
    classpath += project(':rss-middletier').sourceSets.main.runtimeClasspath
    jvmArgs '-DoutputDirectory=' + project(':rss-middletier').sourceSets
        .main.output.classesDir.getPath()
}

只有在我检测了这些类之后,我才会想要将它们打包到一个 JAR 文件中。有没有办法让我可以在包装之前做这个检测?

非常感谢!!!

【问题讨论】:

  • 这里是一个 Gradle 项目示例:github.com/javalite/activejdbc-gradle。如果你执行:gradle clean build jar,它将生成一个带有检测类的 jar 文件
  • 使用配置 { jar } 然后 jar.doFirst { dependsOn instrument }

标签: java jar gradle build.gradle activejdbc


【解决方案1】:

终于找到办法了!

task instrument(type: JavaExec) {
    //your instrumentation task steps here
}
compileJava.doLast {
    tasks.instrument.execute()
}
jar {
    //whatever jar actions you need to do
}

希望这可以防止其他人在这个问题上卡住几天:)

【讨论】:

    【解决方案2】:

    这与问题中的问题有点无关。但是想通过思考来提及它可能对某人有所帮助。

    我试图在 Jar 任务之前执行类型为 Copy 的任务。

    task copyFilesTask(type: Copy) {
    
       //do whatever you want in here
    }
    
    compileJava.dependsOn(copyFilesTask)
    
    jar {
        // jar actions. example below
        //manifest {
        //    attributes 'Main-Class': '<target-class-name-here>'
        //}
    }
    

    我在compileJava 任务之前完成了这项工作,因为我需要在创建 jar 存档时相关文件可用。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2020-07-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-03-02
      • 2014-08-11
      • 1970-01-01
      相关资源
      最近更新 更多