Sub topic 2
Compiling and Running a Native Executable
Assume Java 17+, Spring Boot 3, and basic Maven or Gradle knowledge. A native executable contains compiled application code and does not require a JVM at runtime.
Compiling and Running a Native Executable
Maven uses the native profile to run GraalVM Native Image. The command creates an executable under target.
./mvnw -Pnative native:compile
./target/demoWith Gradle, apply the GraalVM Native Build Tools plugin and run:
./gradlew nativeCompile
./build/native/nativeCompile/demoNative compilation usually takes longer than JVM compilation. The result often starts faster and uses less memory, which suits short-lived services and serverless workloads.
Building a Native Container Image
Cloud Native Buildpacks can compile the application and package it as an OCI container image. OCI is a standard format for container images.
./mvnw -Pnative spring-boot:build-imageThe Maven command uses a builder image, so a local GraalVM installation is not required. You still need a container runtime such as Docker or Podman. The Gradle equivalent is:
./gradlew bootBuildImageRun the resulting image with your container tool and configure its exposed port as usual.
What Gets Fixed at Build Time
Spring AOT, or ahead-of-time processing, analyzes the application during the build. It generates code and metadata that replace some runtime discovery.
Conditions on beans can therefore be evaluated during the native build. For example, a bean controlled by app.feature.enabled may exist only if that property is true during the build. Changing the property later cannot add a bean that was excluded. Rebuild when changing profiles or build-time conditional configuration.
Reachability Metadata
GraalVM assumes a closed world: it compiles code it can prove is reachable. Reflection, classpath resources, and dynamic proxies can hide reachability from static analysis.
Spring usually supplies hints for common framework features. Register application-specific usage with RuntimeHintsRegistrar.
@Configuration
@ImportRuntimeHints(AppConfig.GreetingHints.class)
class AppConfig {
static class GreetingHints implements RuntimeHintsRegistrar {
public void registerHints(RuntimeHints h, ClassLoader loader) {
h.reflection().registerType(Greeting.class,
MemberCategory.INVOKE_PUBLIC_CONSTRUCTORS,
MemberCategory.INVOKE_PUBLIC_METHODS);
h.resources().registerPattern("templates/greeting.txt");
}
}
record Greeting(String text) {}
}Custom dynamic proxies also need metadata. Missing metadata commonly causes native-only startup or runtime failures.
Exercise
Why can changing a conditional property after native compilation fail to create a bean?
Show answer
Spring AOT evaluated the condition during the build and compiled the resulting bean graph into the executable.