此版本仍在开发中,尚未被视为稳定版本。如需最新稳定版本,请使用 Spring Boot 4.0.4!spring-doc.cadn.net.cn

高级原生镜像主题

嵌套配置属性

Spring 的预先(ahead-of-time)引擎会自动为配置属性创建反射提示。 然而,对于非内部类的嵌套配置属性,必须使用 @NestedConfigurationProperty 进行注解,否则它们将无法被检测到,也无法进行绑定。spring-doc.cadn.net.cn

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 是:spring-doc.cadn.net.cn

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 方法。spring-doc.cadn.net.cn

使用构造函数绑定时,您必须使用 @NestedConfigurationProperty 注解字段:spring-doc.cadn.net.cn

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 注解参数:spring-doc.cadn.net.cn

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 注解数据类的参数:spring-doc.cadn.net.cn

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转换为原生镜像。 这在许多情况下都非常有用,包括:spring-doc.cadn.net.cn

  • 您可以保留常规的 JVM 流水线,并在您的 CI/CD 平台上将 JVM 应用程序转换为原生镜像。spring-doc.cadn.net.cn

  • 由于 native-image 不支持交叉编译,您可以保留一个与操作系统无关的部署制品,稍后将其转换为不同的操作系统架构。spring-doc.cadn.net.cn

您可以使用 Cloud Native Buildpacks,或使用 GraalVM 附带的 native-image 工具,将 Spring Boot 可执行 jar 转换为原生镜像。spring-doc.cadn.net.cn

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

使用 Buildpacks

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

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

首先,确保可用的Docker守护进程(有关详细信息,请参阅 获取Docker)。 如果在Linux上,请配置它以允许非根用户spring-doc.cadn.net.cn

您还需要按照 buildpacks.io 上的安装指南 安装 packspring-doc.cadn.net.cn

假设一个经过AOT处理的Spring Boot可执行jar文件以myproject-0.0.1-SNAPSHOT.jar的形式存在于target目录中,运行:spring-doc.cadn.net.cn

$ 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 启动应用程序:spring-doc.cadn.net.cn

$ 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!等下载管理器。spring-doc.cadn.net.cn

假设一个经过AOT处理的Spring Boot可执行jar文件以myproject-0.0.1-SNAPSHOT.jar的形式存在于target目录中,运行:spring-doc.cadn.net.cn

$ 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-doc.cadn.net.cn

当使用代理为原生镜像生成提示时,有几种方法:spring-doc.cadn.net.cn

第一种选项在 Spring 无法识别某个库或模式时,有助于识别缺失的提示。spring-doc.cadn.net.cn

第二种选项对于可重复的设置来说更具吸引力,但默认情况下生成的提示信息将包括测试基础设施所需的一切内容。 当应用程序实际运行时,其中一些内容将是不必要的。 为了解决这个问题,代理支持一个访问过滤器文件,该文件将导致某些数据被排除在生成的输出之外。spring-doc.cadn.net.cn

直接启动应用程序

使用以下命令启动应用程序,并附加原生镜像跟踪代理:spring-doc.cadn.net.cn

$ 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 停止应用程序。spring-doc.cadn.net.cn

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

可以对原生图像跟踪代理设置更多高级选项,例如按调用者类过滤记录的提示等。 如需进一步阅读,请参阅 官方文档spring-doc.cadn.net.cn

自定义提示

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

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 type for java serialization
		hints.reflection().registerJavaSerialization(MySerializableClass.class);

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

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

}

您可以随后在任何 @Configuration 类上使用 @ImportRuntimeHints(例如您的 @SpringBootApplication 注解的应用程序类)来激活这些提示。spring-doc.cadn.net.cn

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

测试自定义提示

RuntimeHintsPredicates API 可用于测试您的提示。 该 API 提供了构建 Predicate 的方法,该方法可用于测试 RuntimeHints 实例。spring-doc.cadn.net.cn

如果您使用的是 AssertJ,您的测试代码将如下所示:spring-doc.cadn.net.cn

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/spring-doc.cadn.net.cn

已知限制

GraalVM原生镜像是一个不断发展完善的技术,不是所有库都提供支持。 GraalVM社区通过为尚未提供自身支持的项目提供可达性元数据来帮助。 Spring本身不包含对第三方库的提示,而是依赖于可达性元数据项目。spring-doc.cadn.net.cn

如果您在为 Spring Boot 应用程序生成本机映像时遇到问题,请查看 Spring Boot wiki 的 Spring Boot with GraalVM 页面。 您还可以向 GitHub 上的 spring-aot-smoke-tests 项目提交问题,该项目用于确认常见应用程序类型是否按预期工作。spring-doc.cadn.net.cn

如果您发现某个与GraalVM不兼容的库,请在 可达性元数据项目 上提出问题。spring-doc.cadn.net.cn