Issue
I have created a Spring Boot
project using Kotlin
. I would like to create a .jar
file with all the dependencies so that I can run the application from the command line. The FQCN for the main class is: com.example.Application.kt
. I have following configuration in my pom.xml
:
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
<configuration>
<mainClass>com.example.Application</mainClass>
</configuration>
<executions>
<execution>
<goals>
<goal>repackage</goal>
</goals>
</execution>
</executions>
</plugin>
The application fails to start complaining that the mainClass was not found. Here is the sample exception:
Exception in thread "main" java.lang.ClassNotFoundException: com.example.Application
at java.base/java.net.URLClassLoader.findClass(URLClassLoader.java:471)
at java.base/java.lang.ClassLoader.loadClass(ClassLoader.java:588)
at org.springframework.boot.loader.LaunchedURLClassLoader.loadClass(LaunchedURLClassLoader.java:93)
at java.base/java.lang.ClassLoader.loadClass(ClassLoader.java:521)
at org.springframework.boot.loader.MainMethodRunner.run(MainMethodRunner.java:46)
at org.springframework.boot.loader.Launcher.launch(Launcher.java:87)
at org.springframework.boot.loader.Launcher.launch(Launcher.java:51)
at org.springframework.boot.loader.JarLauncher.main(JarLauncher.java:52)
What am I missing?
Solution
I am just attempting to learn Kotlin myself, but I suspect you may need to append Kt
to the end of your classname. For example:
<manifest>
<mainClass>com.example.ApplicationKt</mainClass>
</manifest>
Unrelated to Spring, I encountered this issue myself when attempting to build an executable JAR. If you unzip your JAR and look at the class files, I believe you will find an ApplicationKt.class
.
If so, this is because you did not define the main
function within a class. In this scenario, Kotlin generates a static method belonging to a <filename>Kt.class
version of your file. According to this SO answer:
Unlike Java, Kotlin allows you to define functions that are not inside a class. But if you want Java to talk to Kotlin that becomes a problem. How to solve it? Convert those functions into static methods of a class named as the file with the "Kt" suffix
You can find more info about that in the documentation
Answered By - Miles_Dowe