在 Java 中自定义 Gradle 基于插件的 ZipTask

Custom Gradle Plugin based ZipTask in Java

我想在 Java 中创建一个自定义 Gradle 插件,它只会创建一个 Zip 任务。

DSL版本如下:

task _3_buildZip(type: Zip) {
   from compileJava
   from processResources
   into('lib') {
      from configurations.runtimeClasspath
      from('build.properties')
   }
}

到目前为止,我创建了以下无效的代码:-(

import org.gradle.api.Plugin;
import org.gradle.api.Project;
import org.gradle.api.tasks.bundling.Zip;

public class ZipTaskPlugin implements Plugin<Project> {
    @Override
    public void apply(Project project) {

        Zip zipTask = project.getTasks().create("HelloZipWorld",Zip.class);
        zipTask.from(project.getComponents().getByName("java"));
        zipTask.from(project.getComponents().getByName("resources"));
        zipTask.into("lib").from(project.getConfigurations());

    }
}

请指教

终于自己解决了。在这里分享给大家。

import org.gradle.api.Plugin;
import org.gradle.api.Project;
import org.gradle.api.file.CopySpec;
import org.gradle.api.plugins.JavaPlugin;
import org.gradle.api.tasks.bundling.Zip;

public class ZipTaskPlugin implements Plugin<Project> {
    @Override
    public void apply(Project project) {

        Zip task= project.getTasks().create( "HelloZipWorld", Zip.class );

        task.into(task.getArchiveFileName().get(), (CopySpec copySpec) ->{
                    copySpec.into("lib")
                            .from(project.getConfigurations().getByName(JavaPlugin.RUNTIME_CLASSPATH_CONFIGURATION_NAME))
                            .from("build.properties");
                })
                .from(project.getTasks().getByName(JavaPlugin.COMPILE_JAVA_TASK_NAME))
                .from(project.getTasks().getByName(JavaPlugin.PROCESS_RESOURCES_TASK_NAME))
        ;
    }
}