New Maven Project

Basics for developing Kotlin apps with Maven

Updated: 03 September 2023

Maven is a build tool for Java applications. The creation of maven projects can be done using the CLI and templates called Archetypes

Init Project

To create a Kotlin/Maven project you can use the following command, provided:

  • Archetype: kotlin-archetype-jvm
  • Archetype Group ID: org.jetbrains.kotlin
  • Archetype Version: 1.4.32
  • Project Group ID: com.mycompany
  • Artifact ID: demo
  • Output Directory: .
Terminal window
1
mvn archetype:generate -DarchetypeArtifactId=kotlin-archetype-jvm -DarchetypeGroupId=org.jetbrains.kotlin -DarchetypeVersion=1.4.32 -DgroupId=com.mycompany -DartifactId=demo -DoutputDirectory=.

Which will create a project based on the template in the ./demo directory

Additionally, VSCode’s Maven for Java extension also contains the Maven: Create Maven Project command which enables you to configure the entire project as well as search the Archetype repository for templates, I would recommend this over the command line method

Self Contained JAR

To ensure your code builds to a self-contained JAR and that the main function is executable, you should add the following to the build>plugins section of your pom.xml file:

1
<plugin>
2
<groupId>org.apache.maven.plugins</groupId>
3
<artifactId>maven-assembly-plugin</artifactId>
4
<version>2.6</version>
5
<executions>
6
<execution>
7
<id>make-assembly</id>
8
<phase>package</phase>
9
<goals> <goal>single</goal> </goals>
10
<configuration>
11
<archive>
12
<manifest>
13
<mainClass>${main.class}</mainClass>
14
</manifest>
15
</archive>
16
<descriptorRefs>
17
<descriptorRef>jar-with-dependencies</descriptorRef>
18
</descriptorRefs>
19
</configuration>
20
</execution>
21
</executions>
22
</plugin>

You’ll also need to set the main.class property in your properties section so that the build knows what to set it as in the above plugin we defined, this is made up of the Project Group ID + the name of the file with Kt appended to refer to the compiled Kotlin class, so in the starter app it will be com.mycompany.HelloKt:

1
<properties>
2
... other stuff
3
<main.class>com.mycompany.HelloKt</main.class>
4
</properties>

Verify

The verify command will run through all the build workflows that are configured, you can run:

Terminal window
1
mvn verify

This will test/package the application for you

Build

If you want to specicically build a jar file, you do this with the package command:

Terminal window
1
mvn package

Run

Once you’ve packaged your application, you can use the following to run it:

Terminal window
1
java -jar target/appname-jar-with-dependencies.jar

Clean

Lastly, to clean all build artifacts you can just use:

Terminal window
1
mvn clean