高级原生镜像主题
原文:https://docs.spring.io/spring-boot/reference/packaging/native-image/advanced-topics.html (Spring Boot 4.2.0)
嵌套配置属性
配置属性的反射提示由 Spring 提前处理引擎自动创建。但是,不是内部类的嵌套配置属性必须使用 @NestedConfigurationProperty 注解,否则它们不会被检测,也无法绑定:
@ConfigurationProperties("my.properties") public class MyProperties { private String name; @NestedConfigurationProperty private final Nested nested = new Nested(); // getters / setters... }
其中 Nested 是一个普通的 Java 类。上面的示例会生成 my.properties.nested.* 的配置属性。
将 Spring Boot 可执行 Jar 转换为原生镜像
可以使用以下方式将可执行 jar 转换为原生镜像。
使用 Buildpacks
Paketo Java buildpack 可以检测包含 AOT 生成代码的 jar 并自动构建原生镜像。可以通过设置 BP_NATIVE_IMAGE=true 环境变量启用。
使用 GraalVM native-image
可以直接使用 GraalVM 的 native-image 工具从可执行 jar 构建原生镜像:
$ native-image -jar my-app.jar
通常需要先执行 AOT 处理(例如 mvn -Pnative native:compile),以便生成必要的提示文件和源代码。
使用 Tracing Agent
GraalVM 的 tracing agent 可以在 JVM 上运行应用时记录反射、资源和代理的使用情况,并生成相应的配置文件。
直接启动应用
可以通过 -agentlib:native-image-agent=config-output-dir=... 参数启动应用以启用 tracing agent:
$ java -agentlib:native-image-agent=config-output-dir=./config -jar my-app.jar
然后运行应用的各种代码路径,agent 会生成配置文件,可在构建原生镜像时使用。
自定义提示
可以通过实现 RuntimeHintsRegistrar 接口以编程方式提供自定义反射、资源或代理提示:
public class MyRuntimeHints implements RuntimeHintsRegistrar { @Override public void registerHints(RuntimeHints hints, ClassLoader classLoader) { hints.reflection().registerType(MyClass.class, MemberCategory.INVOKE_DECLARED_CONSTRUCTORS, MemberCategory.INVOKE_PUBLIC_METHODS); } }
测试自定义提示
可以使用 ApplicationContextRunner 或 @ImportRuntimeHints 在测试中验证自定义提示。
静态提供提示
可以在 META-INF/spring/aot.factories 中声明 RuntimeHintsRegistrar 实现,或在配置类上使用 @ImportRuntimeHints 注解。
已知限制
原生镜像有一些已知限制,包括:
- 不支持动态类加载和自定义类加载器。
- 某些反射用法需要显式提示。
- 不支持所有 JVM 特性(如某些 instrumentation)。
- 配置文件和资源必须显式包含。
- 动态代理需要提前声明。