In cloud native development generally we want to develop small and succinct micro services that are specialized on a particular functionality. There might be some applications built using plain old Java with servlets. We will be able to operate and maintain them. There are many cases where we want to create a multi module project targeted to deploy each module in a different cloud environment. Or there can be a need to develop reusable multiple module non executable jars meant to include in executable applications. The first step is to be able to create a single module executable and deployable Java applications as a jar file. In this blog I will show what is the minimum requirement to create and bundle an executable Java application using an example.
Project Structure
After we create a maven project the project structure will look like as shown below. Here I am using IntelliJ IDE but you can use any IDE of your choice. We will just create a Main class with a main method and a pom.xml for the project.
The code
The Main class
package com.dibyo.java.single.executable;
public class Main {
public static void main(String[] args) {
System.out.println("Hello !");
}
}
The POM.XML
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0
http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.dibyo.java.single.executable</groupId>
<artifactId>single-module</artifactId>
<version>1.0-SNAPSHOT</version>
<properties>
<maven.compiler.source>12</maven.compiler.source>
<maven.compiler.target>12</maven.compiler.target>
</properties>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-jar-plugin</artifactId>
<configuration>
<archive>
<manifest>
<addClasspath>true</addClasspath>
<classpathPrefix>/</classpathPrefix>
<mainClass>
com.dibyo.java.single.executable.Main
</mainClass>
</manifest>
</archive>
</configuration>
<executions>
<execution>
<goals><goal>jar</goal></goals>
</execution>
</executions>
</plugin>
</plugins>
</build>
</project>
Creating An Executable Jar
We need to go to the root directory and execute the maven command
<path>/single-module > mvn clean install
It will build a jar named single-module-1.0-SNAPSHOT.jar under a target sub folder
How to Run
We will go to the target folder and run the jar file
<path>/single-module/target >java -jar single-module-1.0-SNAPSHOT.jar
And we will get the output as desired
Hello !
So, we have learned here how to create a single module executable jar for a Java application.
Comments