0Pricing
Spring Boot 4 Complete Guide · 课时

反射与资源的运行时提示

注册反射、代理和资源提示,确保动态功能在原生编译后仍可用。

反射与资源的运行时提示 是 CoddyKit 上的免费 Spring Boot 4 Complete Guide 课时。 这是第 2 节课,共 4 节。 你可以在下方免费阅读本课时的完整内容 — 然后在浏览器中使用内置代码编辑器和全天候 AI 导师进行实践。 这是 Spring Boot 4 Complete Guide 学习路径的一部分,你的进度在网页和 CoddyKit 应用中同步。 Spring Boot 4 Complete Guide 课程共包含 4 节课。

本课时的部分内容尚未翻译,以英文显示。

Why Native Images Break Reflection

GraalVM native compilation uses closed-world analysis: at build time it must see every class, method, and field that could ever be reached. Code paths it cannot statically prove are reachable are removed from the final binary.

  • Reflection (Class.forName, getDeclaredMethod) hides the target from static analysis.
  • Dynamic proxies generated at runtime have no class to scan at build time.
  • Resources loaded via getResourceAsStream are not bundled unless declared.

The fix is to feed the analyzer explicit metadata called runtime hints, so it keeps these elements in the image.

What Spring Boot Contributes Automatically

Spring Boot 4 and the AOT (ahead-of-time) engine already register hints for most framework internals: @Component beans, @ConfigurationProperties classes, Jackson-bound DTOs reached through controllers, and auto-configuration classes.

You only write your own hints when you do something the AOT engine cannot trace, such as:

  • Reflectively instantiating a class you load by name from config.
  • Serializing a type that no controller or repository references.
  • Reading a non-classpath-scanned resource file at runtime.
  • Creating a JDK dynamic proxy for an interface you build yourself.

The RuntimeHintsRegistrar Interface

The primary programmatic entry point is RuntimeHintsRegistrar. You implement a single method, registerHints, which receives a RuntimeHints object exposing sub-registries for reflection, resources, proxies, serialization, and resource bundles.

The ClassLoader parameter lets you conditionally register only when a type is actually present on the classpath.

package com.example.demo.hints;

import org.springframework.aot.hint.RuntimeHints;
import org.springframework.aot.hint.RuntimeHintsRegistrar;

public class MyRuntimeHints implements RuntimeHintsRegistrar {

    @Override
    public void registerHints(RuntimeHints hints, ClassLoader classLoader) {
        // reflection, resources and proxies are registered here
    }
}

Registering Reflection Hints

Use hints.reflection().registerType(...) and pass the member categories you need. Categories are coarse-grained switches that tell GraalVM which members to keep reflectively accessible.

  • INVOKE_DECLARED_CONSTRUCTORS — keep constructors callable.
  • INVOKE_DECLARED_METHODS — keep methods invokable.
  • DECLARED_FIELDS — keep fields readable/writable.

Grant only what you actually use; over-broad hints bloat the image.

import org.springframework.aot.hint.MemberCategory;
import org.springframework.aot.hint.RuntimeHints;
import org.springframework.aot.hint.RuntimeHintsRegistrar;

public class ReflectionHints implements RuntimeHintsRegistrar {

    @Override
    public void registerHints(RuntimeHints hints, ClassLoader classLoader) {
        hints.reflection().registerType(
            com.example.demo.PaymentProcessor.class,
            MemberCategory.INVOKE_DECLARED_CONSTRUCTORS,
            MemberCategory.INVOKE_DECLARED_METHODS);
    }
}

Activating Hints with @ImportRuntimeHints

A registrar does nothing until Spring is told to run it. Annotate any configuration or component class with @ImportRuntimeHints, referencing your registrar. The AOT engine then invokes it during the build.

Place it next to the code that needs the hint so the relationship stays discoverable.

import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.ImportRuntimeHints;

@Configuration
@ImportRuntimeHints(ReflectionHints.class)
public class PaymentConfig {
    // beans that rely on reflective access to PaymentProcessor
}

Conditional Registration with TypeReference

If a class might be absent at build time, register it by name using TypeReference instead of a hard .class literal. Combine with a presence check so the hint is only added when the type is on the classpath.

This pattern is common in starter libraries that adapt to optional dependencies.

import org.springframework.aot.hint.MemberCategory;
import org.springframework.aot.hint.RuntimeHints;
import org.springframework.aot.hint.RuntimeHintsRegistrar;
import org.springframework.aot.hint.TypeReference;
import org.springframework.util.ClassUtils;

public class OptionalHints implements RuntimeHintsRegistrar {

    @Override
    public void registerHints(RuntimeHints hints, ClassLoader classLoader) {
        if (ClassUtils.isPresent("com.example.optional.LegacyAdapter", classLoader)) {
            hints.reflection().registerType(
                TypeReference.of("com.example.optional.LegacyAdapter"),
                MemberCategory.INVOKE_DECLARED_CONSTRUCTORS);
        }
    }
}

Registering Resource Hints

Files loaded with getResourceAsStream or ClassPathResource must be declared, or they vanish from the native binary. Register exact paths or glob-style patterns through hints.resources().

  • registerPattern("config/*.json") — include matching classpath resources.
  • registerResource(...) — include a single known Resource.
import org.springframework.aot.hint.RuntimeHints;
import org.springframework.aot.hint.RuntimeHintsRegistrar;

public class ResourceHints implements RuntimeHintsRegistrar {

    @Override
    public void registerHints(RuntimeHints hints, ClassLoader classLoader) {
        hints.resources()
             .registerPattern("templates/email/*.html")
             .registerPattern("data/countries.json");
    }
}

Registering Proxy Hints

JDK dynamic proxies created with Proxy.newProxyInstance need every implemented interface declared, because GraalVM must generate the proxy class at build time. Use hints.proxies().registerJdkProxy(...) with the full interface set.

Spring registers proxies for its own @Transactional and repository interfaces automatically; you only add hints for proxies you create yourself.

import org.springframework.aot.hint.RuntimeHints;
import org.springframework.aot.hint.RuntimeHintsRegistrar;

public class ProxyHints implements RuntimeHintsRegistrar {

    @Override
    public void registerHints(RuntimeHints hints, ClassLoader classLoader) {
        hints.proxies().registerJdkProxy(
            com.example.demo.AuditLog.class,
            com.example.demo.Versioned.class);
    }
}

A Complete Multi-Category Registrar

Real registrars usually combine several hint types. Here a single registrar declares reflection for a dynamically loaded strategy, a resource pattern for its config, and a proxy for an interface the app wires at runtime.

Keeping related hints together documents exactly which dynamic features a feature depends on.

import org.springframework.aot.hint.MemberCategory;
import org.springframework.aot.hint.RuntimeHints;
import org.springframework.aot.hint.RuntimeHintsRegistrar;
import org.springframework.aot.hint.TypeReference;

public class StrategyHints implements RuntimeHintsRegistrar {

    @Override
    public void registerHints(RuntimeHints hints, ClassLoader classLoader) {
        hints.reflection().registerType(
            TypeReference.of("com.example.demo.JsonExportStrategy"),
            MemberCategory.INVOKE_DECLARED_CONSTRUCTORS,
            MemberCategory.INVOKE_DECLARED_METHODS);

        hints.resources().registerPattern("strategies/*.properties");

        hints.proxies().registerJdkProxy(
            com.example.demo.ExportStrategy.class);
    }
}

Hinting Serialization with @RegisterReflectionForBinding

For DTOs that are only reached reflectively (for example via a manually built ObjectMapper outside any controller), the convenience annotation @RegisterReflectionForBinding registers all members needed for Jackson binding in one line, avoiding hand-listing categories.

It is a shortcut that delegates to the same reflection registry under the hood.

import org.springframework.aot.hint.annotation.RegisterReflectionForBinding;
import org.springframework.stereotype.Component;

@Component
@RegisterReflectionForBinding({ InvoiceDto.class, LineItemDto.class })
public class InvoiceExporter {
    // serializes InvoiceDto with a hand-built ObjectMapper
}

Verifying Hints Before Going Native

Compiling a native image is slow, so verify hints on the JVM first. The GraalVM reachability metadata agent records actual reflection/resource access during a normal test run and emits JSON metadata you can compare against your hints.

Spring also offers RuntimeHintsPredicates to assert in a unit test that a given type or resource is registered — fast feedback without a full native build.

import org.junit.jupiter.api.Test;
import org.springframework.aot.hint.RuntimeHints;
import org.springframework.aot.hint.predicate.RuntimeHintsPredicates;
import static org.assertj.core.api.Assertions.assertThat;

class ReflectionHintsTest {

    @Test
    void registersPaymentProcessor() {
        RuntimeHints hints = new RuntimeHints();
        new ReflectionHints().registerHints(hints, getClass().getClassLoader());

        assertThat(RuntimeHintsPredicates.reflection()
                .onType(com.example.demo.PaymentProcessor.class))
            .accepts(hints);
    }
}

Quick Check: Proxy Hints

Your application creates a JDK dynamic proxy for two of your own interfaces using Proxy.newProxyInstance. It works on the JVM but throws at runtime in the native image. Which hint fixes it?

Recap

GraalVM's closed-world analysis strips anything it cannot statically prove reachable, so dynamic features need explicit runtime hints.

  • Implement RuntimeHintsRegistrar.registerHints and activate it with @ImportRuntimeHints.
  • hints.reflection().registerType(...) with the right MemberCategory values keeps reflective constructors, methods, and fields.
  • hints.resources().registerPattern(...) bundles runtime-loaded files.
  • hints.proxies().registerJdkProxy(...) declares custom JDK dynamic proxies.
  • @RegisterReflectionForBinding is a shortcut for serialization DTOs.
  • Verify with RuntimeHintsPredicates and the reachability metadata agent before a costly native build.

常见问题解答

「反射与资源的运行时提示」课时是免费的吗?

是的 — 「反射与资源的运行时提示」的完整文本可在网页上免费阅读。要进行交互式练习(内置代码编辑器和全天候 AI 导师)并解锁 Spring Boot 4 Complete Guide 课程的其余内容,请升级到 CoddyKit PRO。 Spring Boot 4 Complete Guide 课程共包含 4 节课。

「反射与资源的运行时提示」这节课中我会学到什么?

注册反射、代理和资源提示,确保动态功能在原生编译后仍可用。 你通过在浏览器中直接运行的动手代码来练习 Spring Boot 4 Complete Guide,全天候 AI 导师会在你学习这节课的过程中回答你的问题。

学习 Spring Boot 4 Complete Guide 需要有经验吗?

无需任何先前经验。CoddyKit 上的 Spring Boot 4 Complete Guide 课程适合初学者到高级学习者,你可以从这里开始或从头开始,按照自己的节奏学习。 这是第 2 节课,共 4 节。

「反射与资源的运行时提示」课时需要多长时间?

大多数 CoddyKit 课程大约需要 5–10 分钟。每节课都很精短且互动,所以你能稳步进步,并在网页和应用中从离开的地方继续。

我能在这节 Spring Boot 4 Complete Guide 课中编写并运行代码吗?

能。每节 Spring Boot 4 Complete Guide 课都包含内置代码编辑器,你可以在浏览器中直接编写并运行真实代码,并获得即时 AI 反馈 — 无需本地设置。

此课程中的所有课时

  1. AOT 处理与原生构建流水线
  2. 反射与资源的运行时提示
  3. 类数据共享与 JVM 启动调优
  4. 诊断并修复原生兼容性问题
← 返回 Spring Boot 4 Complete Guide