gradlemaven-publish

Configure gradle "maven-publish" plugin directly from my custom plugin


i'm new in gradle and want to create custom gradle plugin that applies maven-publish plugin. Also my plugin should configure maven-publish plugin so that another plugin user should do nothing. And my plugin will automaticly configure maven-publish. I've tried to find any same tutorial but doesn't find. How can I configure maven-publish gradle plugin from my custom plugin?


Solution

  • Configuring other plugins from a custom plugin is extremely common. You should be able to reference any custom plugin out there for examples. For maven-publish specifically, I have created the following example:

    import org.gradle.api.Plugin;
    import org.gradle.api.Project;
    import org.gradle.api.publish.PublishingExtension;
    import org.gradle.api.publish.maven.MavenPublication;
    import org.gradle.api.publish.maven.plugins.MavenPublishPlugin;
    
    import java.net.URI;
    
    public class MyPlugin implements Plugin<Project> {
    
        @Override
        public void apply(Project project) {
            project.getPluginManager().apply(MavenPublishPlugin.class);
    
            project.getExtensions().configure(PublishingExtension.class, publishing -> {
                publishing.repositories(repositories -> {
                    repositories.maven(maven -> {
                       maven.setUrl(URI.create("https://my-publishing-repo.com"));
                    });
                });
                publishing.publications(publications -> {
                    publications.create("mavenJava", MavenPublication.class, mavenJava -> {
                        mavenJava.artifact(project.getTasks().named("bootJar"));
                    });
                });
            });
        }
    
    }
    

    This is equivalent to the following in the Gradle build file (Kotlin DSL):

    plugins {
        `maven-publish`
    }
    
    publishing {
        repositories {
            maven {
                url = uri("https://my-publishing-repo.com")
            }
        }
        publications {
            create<MavenPublication>("mavenJava") {
                artifact(tasks.named("bootJar").get())
            }
        }
    }
    

    Refer to the following guides from my guidance: