Skip to content

Instantly share code, notes, and snippets.

@ArjanSchouten
Created January 13, 2023 11:07
Show Gist options
  • Save ArjanSchouten/c842019b4c0228630fe1140454a6999f to your computer and use it in GitHub Desktop.
Save ArjanSchouten/c842019b4c0228630fe1140454a6999f to your computer and use it in GitHub Desktop.
Native hints for GraalVM using Spring boot 3 native-image support
package com.excellentwebcheck.x.config
import com.google.common.reflect.ClassPath
import org.springframework.aot.hint.*
import org.springframework.context.annotation.Configuration
import org.springframework.context.annotation.ImportRuntimeHints
@Configuration
@ImportRuntimeHints(NativeHints.Companion.NativeHintsRegistrar::class)
class NativeHints {
companion object {
val PACKAGE_PREFIXES = setOf(
"com.excellentwebcheck.x.model",
)
val MEMBER_CATEGORIES = listOf(
MemberCategory.PUBLIC_FIELDS,
MemberCategory.DECLARED_FIELDS,
MemberCategory.INTROSPECT_PUBLIC_CONSTRUCTORS,
MemberCategory.INTROSPECT_DECLARED_CONSTRUCTORS,
MemberCategory.INVOKE_PUBLIC_CONSTRUCTORS,
MemberCategory.INVOKE_DECLARED_CONSTRUCTORS,
MemberCategory.INTROSPECT_PUBLIC_METHODS,
MemberCategory.INTROSPECT_DECLARED_METHODS,
MemberCategory.INVOKE_PUBLIC_METHODS,
MemberCategory.INVOKE_DECLARED_METHODS,
MemberCategory.PUBLIC_CLASSES,
MemberCategory.DECLARED_CLASSES,
).toTypedArray()
class NativeHintsRegistrar : RuntimeHintsRegistrar {
override fun registerHints(hints: RuntimeHints, classLoader: ClassLoader?) {
registerReflectionClasses(hints)
}
/**
* Since we use reactor-rabbitmq and do a lot of jackson serialization/deserialization ourself, we need
* to manually register model classes for reflection for GraalVM. To make it easier to not forget new classes
* we just register all model classes.
*/
private fun registerReflectionClasses(hints: RuntimeHints) {
val loader = Thread.currentThread().contextClassLoader
ClassPath.from(loader).topLevelClasses.forEach { info ->
PACKAGE_PREFIXES.forEach { packagePrefix ->
if (info.name.startsWith(packagePrefix)) {
val clazz: Class<*> = info.load()
hints.reflection().registerType(TypeReference.of(clazz), *MEMBER_CATEGORIES)
}
}
}
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment