Search code examples
mavengradlejarnexus

How can I build a JAR library with dependencies with Gradle?


I have a Java project, and I need to publish it to a Nexus repository. Now I have two options: build a plain JAR file with .class files only or build a fat JAR file. Is there a third option that allows to include the build.gradle or pom.xml file in my JAR file which would specify required dependencies from that Nexus for my library?

I'm not sure that is how libraries work, but I unzipped some libraries from Maven Central. They are not fat JAR files, but they contain pom.xml files.

Are libraries ever published to the Maven repository built with Gradle that depends on other libraries?


Solution

  • You can use the Maven Publishing Plugin in Gradle.

    Here's an example of how you can configure your build.gradle file to publish your library to a Nexus repository with its POM file.

    Update to yours:

    apply plugin: 'java'
    apply plugin: 'maven-publish'
    
    group = 'com.your group package' // Set your group ID
    version = '1.2.0' // Set your version
    
    publishing {
        publications {
            mavenJava(MavenPublication) {
                from components.java
    
                // Set the POM configuration
                pom {
                    withXml {
                        // Add dependencies to the POM file
                        def dependenciesNode = asNode().appendNode('dependencies')
    
                        // Add each dependency to the POM file
                        configurations.compile.getResolvedConfiguration().firstLevelModuleDependencies.each { dependency ->
                            def dependencyNode = dependenciesNode.appendNode('dependency')
                            dependencyNode.appendNode('groupId', dependency.moduleGroup)
                            dependencyNode.appendNode('artifactId', dependency.moduleName)
                            dependencyNode.appendNode('version', dependency.moduleVersion)
                        }
                    }
                }
            }
        }
    
        repositories {
            maven {
                // Set your Nexus repository URL
                url 'http://your nexus repository url'
    
                // you can set the repository credentials if necessary
                credentials {
                    username 'your username'
                    password 'your password'
                }
            }
        }
    }

    Then run ./gradlew publish to publish your library to the Nexus repository.