高级原生镜像主题

嵌套配置属性

Spring AOT 引擎会自动为配置属性创建反射提示。但是,非内部类的嵌套配置属性**必须**使用 @NestedConfigurationProperty 进行注解,否则它们将无法被检测到,也无法绑定。

import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.context.properties.NestedConfigurationProperty;

@ConfigurationProperties("my.properties")
public class MyProperties {

	private String name;

	@NestedConfigurationProperty
	private final Nested nested = new Nested();

	// getters / setters...

	public String getName() {
		return this.name;
	}

	public void setName(String name) {
		this.name = name;
	}

	public Nested getNested() {
		return this.nested;
	}

}

其中 Nested

  • Java

  • Kotlin

public class Nested {

	private int number;

	// getters / setters...

	public int getNumber() {
		return this.number;
	}

	public void setNumber(int number) {
		this.number = number;
	}

}
class Nested {
}

上面的例子为 my.properties.namemy.properties.nested.number 生成配置属性。如果 nested 字段没有 @NestedConfigurationProperty 注解,那么 my.properties.nested.number 属性将无法在原生镜像中绑定。你也可以注解 getter 方法。

使用构造函数绑定时,你必须使用 @NestedConfigurationProperty 注解字段

import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.context.properties.NestedConfigurationProperty;

@ConfigurationProperties("my.properties")
public class MyPropertiesCtor {

	private final String name;

	@NestedConfigurationProperty
	private final Nested nested;

	public MyPropertiesCtor(String name, Nested nested) {
		this.name = name;
		this.nested = nested;
	}

	// getters / setters...

	public String getName() {
		return this.name;
	}

	public Nested getNested() {
		return this.nested;
	}

}

使用记录时,你必须使用 @NestedConfigurationProperty 注解参数

import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.context.properties.NestedConfigurationProperty;

@ConfigurationProperties("my.properties")
public record MyPropertiesRecord(String name, @NestedConfigurationProperty Nested nested) {

}

使用 Kotlin 时,你需要使用 @NestedConfigurationProperty 注解数据类的参数

import org.springframework.boot.context.properties.ConfigurationProperties
import org.springframework.boot.context.properties.NestedConfigurationProperty

@ConfigurationProperties("my.properties")
data class MyPropertiesKotlin(
	val name: String,
	@NestedConfigurationProperty val nested: Nested
)
在所有情况下,请使用公共的 getter 和 setter,否则属性将无法绑定。

转换 Spring Boot 可执行 Jar

只要 jar 包含 AOT 生成的资源,就可以将 Spring Boot 可执行 jar 转换为原生镜像。这在许多情况下都很有用,包括:

  • 你可以保留常规的 JVM 管道,并在 CI/CD 平台上将 JVM 应用程序转换为原生镜像。

  • 由于 native-image 不支持交叉编译,你可以保留一个与操作系统无关的部署工件,以后再将其转换为不同的操作系统架构。

你可以使用 Cloud Native Buildpacks 或 GraalVM 附带的 native-image 工具将 Spring Boot 可执行 jar 转换为原生镜像。

你的可执行 jar 必须包含 AOT 生成的资源,例如生成的类和 JSON 提示文件。

使用 Buildpacks

Spring Boot 应用程序通常通过 Maven (mvn spring-boot:build-image) 或 Gradle (gradle bootBuildImage) 集成使用 Cloud Native Buildpacks。但是,你也可以使用 pack 将 AOT 处理过的 Spring Boot 可执行 jar 转换为原生容器镜像。

你必须使用至少 JDK 25 构建应用程序,因为 Buildpacks 使用与用于编译的 Java 版本相同的 GraalVM native-image 版本。

首先,请确保 Docker 守护进程可用(有关详细信息,请参阅 获取 Docker)。如果你在 Linux 上,请将其配置为允许非 root 用户

你还需要按照 buildpacks.io 上的安装指南 安装 pack

假设一个 AOT 处理过的 Spring Boot 可执行 jar (myproject-0.0.1-SNAPSHOT.jar) 位于 target 目录中,运行

$ pack build --builder paketobuildpacks/builder-noble-java-tiny \
    --path target/myproject-0.0.1-SNAPSHOT.jar \
    --env 'BP_NATIVE_IMAGE=true' \
    my-application:0.0.1-SNAPSHOT
你无需本地安装 GraalVM 即可通过这种方式生成镜像。

pack 完成后,你可以使用 docker run 启动应用程序

$ docker run --rm -p 8080:8080 docker.io/library/myproject:0.0.1-SNAPSHOT

使用 GraalVM native-image

将 AOT 处理过的 Spring Boot 可执行 jar 转换为原生可执行文件的另一个选项是使用 GraalVM native-image 工具。为此,你的机器上需要有 GraalVM 发行版。你可以从 Liberica Native Image Kit 页面 手动下载,或者使用 SDKMAN! 等下载管理器。

假设一个 AOT 处理过的 Spring Boot 可执行 jar (myproject-0.0.1-SNAPSHOT.jar) 位于 target 目录中,运行

$ rm -rf target/native
$ mkdir -p target/native
$ cd target/native
$ jar -xvf ../myproject-0.0.1-SNAPSHOT.jar
$ native-image -H:Name=myproject @META-INF/native-image/argfile -cp .:BOOT-INF/classes:`find BOOT-INF/lib | tr '\n' ':'`
$ mv myproject ../
这些命令适用于 Linux 或 macOS 机器,但你需要针对 Windows 进行调整。
@META-INF/native-image/argfile 可能未打包在你的 jar 中。它仅在需要可达性元数据覆盖时才包含在内。
native-image-cp 标志不接受通配符。你需要确保所有 jar 都已列出(上面的命令使用 findtr 来实现此目的)。

使用跟踪代理

GraalVM 原生镜像跟踪代理允许你在 JVM 上拦截反射、资源或代理使用,以生成相关的提示。Spring 应该会自动生成大多数这些提示,但跟踪代理可以用于快速识别缺失的条目。

当使用代理为原生镜像生成提示时,有几种方法

  • 直接启动应用程序并进行操作。

  • 运行应用程序测试以操作应用程序。

第一个选项对于在 Spring 未识别库或模式时识别缺失提示很有用。

第二个选项对于可重复的设置听起来更具吸引力,但默认情况下,生成的提示将包含测试基础设施所需的所有内容。其中一些在应用程序实际运行时是不必要的。为了解决这个问题,代理支持一个访问过滤器文件,该文件将导致某些数据从生成的输出中排除。

直接启动应用程序

使用以下命令启动附加了原生镜像跟踪代理的应用程序

$ java -Dspring.aot.enabled=true \
    -agentlib:native-image-agent=config-output-dir=/path/to/config-dir/ \
    -jar target/myproject-0.0.1-SNAPSHOT.jar

现在你可以练习你想要提示的代码路径,然后使用 ctrl-c 停止应用程序。

在应用程序关闭时,原生镜像跟踪代理会将提示文件写入给定的配置输出目录。你可以手动检查这些文件,或将它们用作原生镜像构建过程的输入。要将它们用作输入,请将它们复制到 src/main/resources/META-INF/native-image/ 目录。下次构建原生镜像时,GraalVM 将考虑这些文件。

原生镜像跟踪代理上可以设置更多高级选项,例如按调用者类过滤记录的提示等。有关进一步阅读,请参阅官方文档

自定义提示

如果你需要为反射、资源、序列化、代理使用等提供自己的提示,你可以使用 RuntimeHintsRegistrar API。创建一个实现 RuntimeHintsRegistrar 接口的类,然后对提供的 RuntimeHints 实例进行适当的调用

import java.lang.reflect.Method;

import org.springframework.aot.hint.ExecutableMode;
import org.springframework.aot.hint.RuntimeHints;
import org.springframework.aot.hint.RuntimeHintsRegistrar;
import org.springframework.util.ReflectionUtils;

public class MyRuntimeHints implements RuntimeHintsRegistrar {

	@Override
	public void registerHints(RuntimeHints hints, ClassLoader classLoader) {
		// Register method for reflection
		Method method = ReflectionUtils.findMethod(MyClass.class, "sayHello", String.class);
		hints.reflection().registerMethod(method, ExecutableMode.INVOKE);

		// Register resources
		hints.resources().registerPattern("my-resource.txt");

		// Register serialization
		hints.serialization().registerType(MySerializableClass.class);

		// Register proxy
		hints.proxies().registerJdkProxy(MyInterface.class);
	}

}

然后,你可以在任何 @Configuration 类(例如你的 @SpringBootApplication 注解的应用程序类)上使用 @ImportRuntimeHints 来激活这些提示。

如果你有需要绑定的类(主要在序列化或反序列化 JSON 时需要),你可以在任何 bean 上使用 @RegisterReflectionForBinding。大多数提示都是自动推断的,例如当从 @RestController 方法接受或返回数据时。但是当你直接使用 WebClientRestClientRestTemplate 时,你可能需要使用 @RegisterReflectionForBinding

测试自定义提示

RuntimeHintsPredicates API 可用于测试你的提示。该 API 提供了构建 Predicate 的方法,该 Predicate 可用于测试 RuntimeHints 实例。

如果你正在使用 AssertJ,你的测试将如下所示

import org.junit.jupiter.api.Test;

import org.springframework.aot.hint.RuntimeHints;
import org.springframework.aot.hint.predicate.RuntimeHintsPredicates;
import org.springframework.boot.docs.packaging.nativeimage.advanced.customhints.MyRuntimeHints;

import static org.assertj.core.api.Assertions.assertThat;

class MyRuntimeHintsTests {

	@Test
	void shouldRegisterHints() {
		RuntimeHints hints = new RuntimeHints();
		new MyRuntimeHints().registerHints(hints, getClass().getClassLoader());
		assertThat(RuntimeHintsPredicates.resource().forResource("my-resource.txt")).accepts(hints);
	}

}

静态提供提示

如果你愿意,可以在一个或多个 GraalVM JSON 提示文件中静态提供自定义提示。这些文件应放置在 src/main/resources/ 中,位于 META-INF/native-image/*/*/ 目录内。在 AOT 处理期间生成的提示会写入名为 META-INF/native-image/{groupId}/{artifactId}/ 的目录中。将你的静态提示文件放置在与此位置不冲突的目录中,例如 META-INF/native-image/{groupId}/{artifactId}-additional-hints/

已知限制

GraalVM 原生镜像是不断发展的技术,并非所有库都提供支持。GraalVM 社区通过为尚未发布自己可达性元数据的项目提供可达性元数据来提供帮助。Spring 本身不包含第三方库的提示,而是依赖可达性元数据项目。

如果你在为 Spring Boot 应用程序生成原生镜像时遇到问题,请查看 Spring Boot Wiki 的 Spring Boot 与 GraalVM 页面。你还可以向 GitHub 上的 spring-aot-smoke-tests 项目提交问题,该项目用于确认常见的应用程序类型是否按预期工作。

如果你发现某个库不适用于 GraalVM,请在可达性元数据项目上提出问题。

© . This site is unofficial and not affiliated with VMware.