How to Make a Java Jar File Executable


Let’s say you have a Java project as follows:

package ms.ao.something;
public class MyProject {
    public static void main(String...args) throws Exception {
        System.out.println("Hello world!");
    }
}

Now you want to build this and make it a self contained executable Jar.

If you do a mvn clean install or mvn clean package, and try and run it as follows:

java -jar target/my-java-1.0-SNAPSHOT.jar

You will get the following error:

no main manifest attribute, in target/my-java-1.0-SNAPSHOT.jar

How to Solve no main manifest attribute error

You can solve this error by adding the following in your pom.xml file:

<build>
    <plugins>
        <plugin>
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-jar-plugin</artifactId>
            <version>3.1.1</version>
            <configuration>
                <archive>
                    <manifest>
                        <addClasspath>true</addClasspath>
                        <classpathPrefix>lib/</classpathPrefix>
                        <mainClass>ms.ao.something.MyProject</mainClass>
                    </manifest>
                </archive>
            </configuration>
        </plugin>
    </plugins>
</build>

Now build your solution like this:

mvn clean install package

Then run your standalone Jar as follows:

java -jar target/my-java-1.0-SNAPSHOT.jar