0Pricing
Spring Boot 4 Complete Guide · درس

تلميحات وقت التشغيل للانعكاس والموارد

سجّل تلميحات الانعكاس والوكلاء والموارد حتى تبقى الميزات الديناميكية بعد التجميع الأصلي

تلميحات وقت التشغيل للانعكاس والموارد درس مجاني في Spring Boot 4 Complete Guide على CoddyKit. هذا هو الدرس 2 من أصل 4. يمكنك قراءة الدرس كاملاً أدناه مجاناً — ثم تمرن عليه مباشرة في المتصفح باستخدام محرر أكواد مدمج ومدرس ذكاء اصطناعي متاح 24/7. هذا الدرس جزء من مسار التعلم في 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.

الأسئلة الشائعة

هل درس «تلميحات وقت التشغيل للانعكاس والموارد» مجاني؟

نعم — نص درس «تلميحات وقت التشغيل للانعكاس والموارد» كامل متاح مجاناً هنا على الويب. لتمرينه بشكل تفاعلي (محرر أكواد مدمج ومدرس ذكاء اصطناعي متاح 24/7) وفتح باقي دورة Spring Boot 4 Complete Guide، انتقل إلى CoddyKit PRO. تتضمن دورة Spring Boot 4 Complete Guide 4 دروس في المجموع.

ماذا ستتعلم في «تلميحات وقت التشغيل للانعكاس والموارد»؟

سجّل تلميحات الانعكاس والوكلاء والموارد حتى تبقى الميزات الديناميكية بعد التجميع الأصلي تتمرن على Spring Boot 4 Complete Guide مع أكواد عملية تشغلها مباشرة في المتصفح، ومدرس ذكاء اصطناعي متاح 24/7 يجيب على أسئلتك أثناء عملك.

هل أحتاج إلى خبرة سابقة لأبدأ Spring Boot 4 Complete Guide؟

لا تُشترط خبرة سابقة. Spring Boot 4 Complete Guide على CoddyKit منظم للمبتدئين حتى المتقدمين، لذا يمكنك البدء من هنا أو من البداية والتقدم بسرعتك الخاصة. هذا هو الدرس 2 من أصل 4.

كم من الوقت يستغرق درس «تلميحات وقت التشغيل للانعكاس والموارد»؟

معظم دروس CoddyKit تستغرق حوالي 5–10 دقائق. كل منها موجز وتفاعلي، لذا تحرز تقدماً مستمراً وتستأنف من حيث توقفت عبر الويب والتطبيق.

هل يمكنني كتابة وتشغيل أكواد في درس Spring Boot 4 Complete Guide هذا؟

نعم. كل درس في Spring Boot 4 Complete Guide يتضمن محرر أكواد مدمج، لذا تكتب وتشغل أكواداً حقيقية مباشرة في متصفحك وتحصل على تعليقات فورية من الذكاء الاصطناعي — بدون إعداد محلي.

جميع الدروس في هذه الدورة

  1. معالجة AOT ومسار البناء الأصلي
  2. تلميحات وقت التشغيل للانعكاس والموارد
  3. مشاركة بيانات الفئات وضبط بدء تشغيل JVM
  4. تشخيص مشكلات التوافق الأصلي وإصلاحها
← العودة إلى Spring Boot 4 Complete Guide