Dwi Wahyudi

Senior Software Engineer (Ruby, Golang, Java)


Recently I have some mini projects using Java, it is deployed in AWS ElasticBeanstalk. It supports Java out of the box, we just need to deploy jar files there in order to do deployment and release.

Overview

These Java projects are quite simple, each project have only 1 entry/starting point, the main method. Each of this Java project has some dependencies/libraries specified in pom.xml.

We need to pack them up in a single executable jar file.

In order to do this we need a packaging plugin provided by maven, called maven-assembly-plugin.

https://maven.apache.org/plugins/maven-assembly-plugin/

Before starting, make sure to have maven installed, thus having mvn executable available in terminal.

Project Spec

First, let’s specify the project specifications in pom.xml, like this:

<modelVersion>4.0.0</modelVersion>
<groupId>com.dwiwahyudi</groupId>
<artifactId>sampleapp</artifactId>
<packaging>jar</packaging>
<version>0.1</version>

Plugin Spec

Then, inside <plugins> tag, we need to use that plugin. Let Say we have the main method inside com.dwiwahyudi.SampleApp.

<plugin>
    <groupId>org.apache.maven.plugins</groupId>
    <artifactId>maven-assembly-plugin</artifactId>
    <executions>
        <execution>
            <phase>package</phase>
            <goals>
                <goal>single</goal>
            </goals>
            <configuration>
                <archive>
                    <manifest>
                        <addClasspath>true</addClasspath>
                        <classpathPrefix>src/</classpathPrefix>
                        <mainClass>
                            com.dwiwahyudi.SampleApp
                        </mainClass>
                    </manifest>
                </archive>
                <descriptorRefs>
                    <descriptorRef>jar-with-dependencies</descriptorRef>
                </descriptorRefs>
            </configuration>
        </execution>
    </executions>
</plugin>

This part will include all .java files inside src directory, compile them into .class files and include them in the jar file.

  <addClasspath>true</addClasspath>
  <classpathPrefix>src/</classpathPrefix>

Building the Project

After this, we can run the following command in terminal.

mvn clean package

The jar file will be available in target/ directory, with name: sampleapp-0.1-with-dependencies.jar

That jar file will contain .class files from our Java code (in src/ directory), plus dependencies/libraries we use in that project.

For new deployment, we just need to change version tag in pom.xml, and run mvn clean package again.