Kotlin scripting adds dynamic power to Spring Boot applications. Imagine adapting your app’s behavior, such as reports at runtime without redeploying—Kotlin scripts make this possible! However, using Kotlin scripts inside Spring Boot fat JARs is challenging. This repository explores practical solutions and invites collaboration to refine and improve them.
Kotlin scripts struggle to load classes from Spring Boot fat JARs. While configuring a custom classloader for Kotlin scripting seems promising, the default Kotlin implementation uses its the standard classloader, making this approach ineffective.
The workaround involves:
-
Unpacking JARs: Extracting the Kotlin JARs embedded in the fat JAR.
-
Copying JARs to Local Filesystem: Using
URLClassLoader
to load classes from these JARs.
Important
|
Don’t mix unpacking and copying JARs in the same project.
(Look for COPY_MIX_FAIL in the logs.)
|
We’ll monitor Kotlin updates to see if this limitation gets resolved.
-
Dynamic Adaptability: Change scripts without restarting the application.
-
Runtime Flexibility: Evaluate and execute scripts dynamically for specific tasks.
Security Warning: Scripts can access your application internals. Secure them to avoid risks.
This project is a step-by-step guide for implementing Kotlin scripting in Spring Boot. It covers:
-
Gradle Configuration: Simplifies fat JAR unpacking and script integration.
-
Practical Examples: Includes sample modules demonstrating unpacking and copying approaches.
-
Pitfalls and Best Practices: Save hours of troubleshooting by learning from our experience.
-
Application: Core Spring Boot app with Gradle config for unpacking JARs.
-
Supports passing variables (e.g., for user authentication in scripts).
-
Includes automatic script timeout to prevent endless execution.
-
-
Business: Demonstrates an unpacked module accessible to scripts (for test purposes, only).
-
Commons & Misc: Shows copied JARs loaded via
URLClassLoader
(for test purposes, only).
To test this project:
-
Clone the repository:
git clone https://github.com/micromata/SpringBoot-KotlinScripting.git
-
Build the app:
./gradlew clean build
-
Run it:
java -jar application/build/libs/application-0.0.1.jar
-
Check the console output for execution details.
Gradle simplifies fat JAR unpacking compared to Maven. After experimenting with both, I found Gradle to be a more developer-friendly solution for this use case.
Stay up-to-date with JetBrains' Kotlin scripting blog: State of Kotlin Scripting 2024.
-
Kotlin scripting
-
Spring Boot scripting
-
Spring Boot fat JAR
-
Spring Boot dynamic runtime
-
Kotlin dynamic evaluation
-
Kotlin script classloader