Search code examples
springspring-bootjenkinsgradlejenkins-cli

Jenkins built jar less size tha Gradle built Jar


I have built an executable jar in my local machine(windows) using command gradlew bootJar.The size of jar is 17,178 Kb

Now I tried to build and run the using jenkins in local machine only.Jar was generated with very less size than gradle built jar.The size of the jar is only 2 Kb.

I tried it by giving task as jar and build in gradle script jenkins.

When I try t run the jar I am getting error like below

Exception in thread "main" java.lang.NoClassDefFoundError: org/springframework/boot/SpringApplication
    at com.example.demo.DemoApplication.main(DemoApplication.java:13)
Caused by: java.lang.ClassNotFoundException: org.springframework.boot.SpringApplication
    at java.net.URLClassLoader.findClass(Unknown Source)
    at java.lang.ClassLoader.loadClass(Unknown Source)
    at sun.misc.Launcher$AppClassLoader.loadClass(Unknown Source)
    at java.lang.ClassLoader.loadClass(Unknown Source)
    ... 1 more

build.gradle:

plugins {
    id 'org.springframework.boot' version '2.2.2.RELEASE'
    id 'io.spring.dependency-management' version '1.0.8.RELEASE'
    id 'java'
}

group = 'com.example'
version = '0.0.1-SNAPSHOT'
sourceCompatibility = '1.8'

repositories {
    mavenCentral()
}

dependencies {
    implementation 'org.springframework.boot:spring-boot-starter-web'
compile group: 'org.springframework.boot', name: 'spring-boot-starter-parent', version: '2.2.2.RELEASE', ext: 'pom'

    testImplementation('org.springframework.boot:spring-boot-starter-test') {
        exclude group: 'org.junit.vintage', module: 'junit-vintage-engine'
    }
}
jar {
    enabled=true
}
jar {
    manifest {
        attributes(
                'Main-Class': 'com.example.demo.DemoApplication'
        )
    }
}

test {
    useJUnitPlatform()
}

Console output of jenkins:

enter image description here

Anyone help me.Thank you


Solution

  • Creating a simple Jar will not work in this case as it will simply package your source code as a jar. What you need is self-contained fat jar.

    Spring boot plugin already ships the task necessary to build the fat jar. You should remove the following code from gradle.

    jar {
        enabled=true
    }
    jar {
        manifest {
            attributes(
                    'Main-Class': 'com.example.demo.DemoApplication'
            )
        }
    }
    

    In your Jenkinsfile, update the command that builds jar to ./gradlew build. If the build is successful, a fat jar will be generated under build/libs directory.