Home > other >  Creating/publishing a jar per Gradle submodule
Creating/publishing a jar per Gradle submodule

Time:05-24

I'm trying to create a Spring Boot Starter project using Gradle, with the intention that each submodule becomes a different library (like how you have spring-boot-starter-web, spring-boot-starter-security, etc).

However I'm having difficulty in getting Gradle to generate the jars properly, and publishing them to a maven repository. Ideally I'd like to use a DRY approach in Gradle, as I'd like the project to automatically generate a jar and publish for each submodule as the starter project grows (as few code changes as possible).

The structure of my project is:

base-repository:
- my-spring-boot-starter-base
- my-spring-boot-starter-module1

And I'd like this to publish the jars: my-spring-boot-starter-base.jar and my-spring-boot-starter-module1.jar.

Base build.gradle:

import org.springframework.boot.gradle.plugin.SpringBootPlugin

plugins {
    id 'org.springframework.boot' version '2.6.7'
    id 'java'
    id 'java-library'
    id 'maven-publish'
}

allprojects {
    apply plugin: 'java'

    repositories {
        mavenCentral()
    }

    bootJar {
        enabled = false
    }
}

subprojects {
    apply plugin: 'java-library'

    dependencies {
        implementation platform(SpringBootPlugin.BOM_COORDINATES)
    }

    jar {
        enabled = true
    }

    publishing {
        publications {
            withSources(MavenPublication) {
                from components.java
            }
        }
        repositories {
            maven {
                url = 'https://my-repo'
            }
        }
    }
}

wrapper {
    gradleVersion = '7.4.2'
}

Base settings.gradle:

rootProject.name = 'my-spring-boot-starter'

include 'my-spring-boot-starter-base'
include 'my-spring-boot-starter-module1'

Both submodules have build.gradle files that look similar to:

dependencies {
   ...
}

The gradle config I have works when you have one submodule, but not multiple. With multiple, the build fails with the following error:

A problem occurred evaluating root project 'my-spring-boot-starter'.
> Maven publication 'withSources' cannot include multiple components

Would appreciate some assistance!

CodePudding user response:

So I found a way to solve my own problem. In the root build.gradle, change to use:

subprojects {
    ...

    publishing {
        publications {
            "$project.name"(MavenPublication) {
                artifactId project.name
                from components.java
            }
        }
        repositories {
            maven {
                url = 'https://my-repo'
            }
        }
    }
}

project.name gets the name of the submodule, and we tell the maven-publish plugin to create an artifact per submodule using this field.

  • Related