Search code examples
javagradleintellij-ideajarmanifest.mf

How can I add external libraries to my jar file using IntelliJ Idea and Gradle?


I do have a Telegram Bot project in my IntelliJ Idea and it runs good inside IDE.

My goal was to build a jar file to test this app outside of my IDE.

After I build my jar file I always encounter same problem -

Exception in thread "main" java.lang.NoClassDefFoundError: com/pengrad/telegrambot/TelegramBot

I use gradle so I do have this in build.gradle (not full list of libs):

dependencies {
...
    implementation 'com.github.pengrad:java-telegram-bot-api:5.0.1'
...
}

Then I go for Project Structure in IntelliJ -> Artifacts -> + sign -> jar -> from module with dependencies

Here is my last screen where as I believe I add dependency for java-telegram-bot-api...

enter image description here

My MANIFEST.MF file is:

Manifest-Version: 1.0
Main-Class: Socrates

So my code works until place where it should use Telegram dependency

I tried to add Class-path to MANIFEST.MF - adding telegram package jar name there adds new issue - java can't find main module

Could you please help me to find right direction?


Solution

  • You could continue down this route of constructing an executable JAR by hand, or you can use the built-in Gradle method for pulling together an executable Java app, which is provided in the Application plugin.

    First make sure this plugin is applied:

    plugins {
        id 'application'
    }
    

    Make sure it knows about your main class:

    application {
        mainClass = 'Socrates' // Use the fully qualified name
    }
    

    Then run the task installDist which installs your app in the build/install folder. This includes a JAR of your code and the dependency JARs, plus some scripts for execution. (See the Distribution plugin documentation, a plugin added by the Application plugin, for further details.)

    The start-up scripts are in the build/install/applicationName/bin directory (replacing applicationName with your Gradle application name), one for Unix systems and one for Windows. These execute the java command with that main class name and a classpath pointing to the dependency JARs in the installation directory.

    So for example on Unix, you can then run the command build/install/applicationName/bin/applicationName to run your app.