Skip to content
Master Spring 7.0.8 Source Code: Setup, Pre-compilation Pitfalls & Debug-Driven Reading Guide

Master Spring 7.0.8 Source Code: Setup, Pre-compilation Pitfalls & Debug-Driven Reading Guide

This comprehensive guide walks through setting up Spring Framework 7.0.8 source code environment with JDK 17/25, Gradle Wrapper, pre-compilation of spring-core and spring-oxm, IDEA import configuration, creating a minimal debug module, and a systematic debug-driven methodology for reading core IoC/AOP flows including the refresh() 12-step lifecycle.

Rain's Path to Java Mastery
Rain's Path to Java Mastery
Rain's Path to Java Mastery

Version Baseline: Spring Framework 7.0.8

The article targets Spring Framework 7.0.8 (the foundation for Spring Boot 4.x) with JDK 17 as minimum (recommend JDK 25), Jakarta EE 11, Gradle 9.5.1 via Wrapper, IntelliJ IDEA 2024.1+ (recommend 2025.3+), Kotlin 2.2, JUnit 6.0. Key insight: Spring 7 uses "17 compile baseline + 25 recommended runtime" — teams can upgrade framework first, then JDK.

Version Cheat Sheet

Spring Framework : 7.0.8 (GA Nov 2025, base for Spring Boot 4.0.x/4.1.x)

JDK : Min 17, recommend 25 (17/21/25 are fully tested LTS; 17 is bytecode baseline, 25 recommended for production/build)

Jakarta EE : 11 (Servlet 6.1/JPA 3.2/Bean Validation 3.1; javax.* fully removed, replaced with jakarta.*)

Gradle : Wrapper locks 9.5.1 (do not install Gradle locally; use gradle-wrapper.properties)

IDEA : 2024.1+, recommend 2025.3+ (native JSpecify null-safety annotation support)

Kotlin/JUnit : Kotlin 2.2, JUnit 6.0

Memory/Disk : 8GB+ RAM, 10GB+ disk (full compile + IDEA indexing are memory intensive)

Notable Changes in 7.0.8

Programmatic Bean Registration (BeanRegistrar / BeanRegistry): Pure Java if/for conditional batch registration, 10x cleaner than BeanDefinitionRegistryPostProcessor

Core Resilience (org.springframework.core.retry, @Retryable, @ConcurrencyLimit): Retry/rate-limiting become first-class citizens, no longer need Spring Retry

API Version Governance (@ApiVersion): Framework-level version routing, no custom interceptors needed

Declarative HTTP Client (@HttpExchange + auto-registration): Official Feign alternative

JmsClient / RestTestClient (org.springframework.jms.JmsClient etc.): Fluent APIs matching JdbcClient/RestClient

JSpecify Null Safety : Replaces JSR 305 and org.springframework.lang annotations; compile-time NullAway validation of @Nullable consistency

Removed spring-jcl : Uses Commons Logging 1.3.0; old articles referencing jcl can be skipped

SpEL Operand Limit 10,000 : Configurable via spring.expression.maxOperations; encountered when reading SpEL source

JDK 25 Features Shadow : Virtual threads, compact object headers delivered via Multi-Release JAR

Technical Note - MRJAR Multi-Source Sets: Java 24+ bytecode reading uses ClassFileMetadataReader (based on JEP 484 Class-File API, replacing trimmed ASM). But spring-core has src/main/java, java21, java24 co-existing (Multi-Release JAR). IDEA navigation may jump to non-runtime-effective source set — verify which source set you're viewing when things don't match.

Environment Setup: Six Steps, None Skippable

3.1 Install JDK: 17 Baseline, 25 Bonus

java -version
# Expect: openjdk version "17.x" or "25.x"

Set JAVA_HOME if version mismatches. Tip: No need to uninstall old JDK; IDEA can assign separate JVM to Gradle.

Pitfall: JDK major version combined with build plugins (especially Kotlin/Dokka) often cause compatibility errors (e.g., "Uninitialized object exists on backward branch"). Principle: Strictly align JDK with project baseline; don't "casually upgrade".

3.2 Get Source: Use Git Tag, Not ZIP

# Full history (for git log tracing, but slow)
git clone https://github.com/spring-projects/spring-framework.git
cd spring-framework
git checkout v7.0.8  # Must checkout release tag, not main

# Shallow clone for code reading only, much faster
git clone --branch v7.0.8 --depth 1 https://github.com/spring-projects/spring-framework.git

Use Gitee mirror if GitHub slow. Three reasons to use Git not ZIP: (1) Build logic depends on Git info; missing .git breaks build metadata. (2) git log/blame are "time machines" for understanding why code was written. (3) Git is most efficient for comparing 7.0.0 → 7.0.8 changes.

⚠️ Note: --depth 1 shallow clone disables git log history. Choose mode per need. After checkout, verify with git branch --show-current (should show detached HEAD at v7.0.8).

3.3 Gradle: Never Install Locally, Use Wrapper

Biggest newbie mistake: downloading Gradle, setting GRADLE_HOME/PATH, causing version mismatches. Spring source includes Gradle Wrapper (four core files):

spring-framework/
├── gradlew          # Linux/Mac script
├── gradlew.bat      # Windows script
└── gradle/
    └── wrapper/
        ├── gradle-wrapper.jar
        └── gradle-wrapper.properties  # Core version config

Verify: ./gradlew --version (Windows: gradlew.bat -v). Should show Gradle 9.x + JVM version.

7.0.8's gradle-wrapper.properties:

distributionBase=GRADLE_USER_HOME
distributionPath=wrapper/dists
distributionUrl=https//services.gradle.org/distributions/gradle-9.5.1-bin.zip
networkTimeout=10000
retries=0
retryBackOffMs=500
validateDistributionUrl=true
zipStoreBase=GRADLE_USER_HOME
zipStorePath=wrapper/dists

Wrapper mechanism: Downloads declared Gradle version on first run, caches in ~/.gradle/wrapper/dists, then delegates to it. Guarantees you, colleagues, CI all use identical Gradle version — eliminates "compiles on my machine but not yours".

Technical Highlight: Wrapper puts Gradle version under version control, ensuring identical Gradle across developer, teammate, CI. Great interview talking point.

Wrapper file roles: gradlew/gradlew.bat = launch scripts; gradle-wrapper.jar = download/verify; gradle-wrapper.properties = declares version/URL. First three shouldn't be hand-edited; upgrade via ./gradlew wrapper --gradle-version x.x.

Pitfall: Old tutorials claim Spring 7 uses Gradle 8.14 — outdated. JDK 25 class file major version 69 requires Gradle 9.1+. 7.0.8 Wrapper locks 9.5.1; trust your local gradle-wrapper.properties.

3.4 Acceleration: Mirrors + Memory, Configure Once

① Give Gradle enough memory + parallel speed in root gradle.properties:

# Give Gradle daemon enough memory (large projects essential)
org.gradle.jvmargs=-Xmx4g -XX:MaxMetaspaceSize=1g -XX:+HeapDumpOnOutOfMemoryError -Dfile.encoding=UTF-8

# Parallel build + build cache + daemon
org.gradle.parallel=true
org.gradle.caching=true
org.gradle.daemon=true

# Disable if not reading Kotlin coroutine source, saves dependencies
kotlin.stdlib.default.dependency=false

Officially recognized speed combo: parallel uses multi-core, cache reuses historical artifacts, daemon avoids repeated JVM cold starts. Real-world: multi-core machines reduce compile from 10+ minutes to few minutes.

② Dependency mirrors. Don't modify source build.gradle; more elegant: inject via user-home ~/.gradle/init.gradle (or ~/.gradle/init.d/) for all Gradle projects:

allprojects {
    repositories {
        mavenLocal()
        maven { url 'https://maven.aliyun.com/repository/public' }
        maven { url 'https://maven.aliyun.com/repository/spring' }
        mavenCentral()
    }
    buildscript {
        repositories {
            maven { url 'https://maven.aliyun.com/repository/public' }
            maven { url 'https://maven.aliyun.com/repository/gradle-plugin' }
        }
    }
}

Also add pluginManagement to settings.gradle top to point plugin repos to mirrors, else plugin downloads often stall:

pluginManagement {
    repositories {
        maven { url 'https://maven.aliyun.com/repository/public' }
        maven { url 'https://maven.aliyun.com/repository/spring' }
        gradlePluginPortal()
        maven { url 'https://repo.spring.io/plugins-release' }
    }
}
Note: Official repos like repo.spring.io MUST be kept; only add mirrors, don't replace entirely, else Spring proprietary artifacts fail to resolve.

③ If Gradle distribution itself won't download (gradle-9.5.1-bin.zip), change Wrapper download URL to domestic mirror:

# gradle/wrapper/gradle-wrapper.properties
distributionUrl=https//mirrors.cloud.tencent.com/gradle/gradle-9.5.1-bin.zip

The backslash in https// is an escape character — keep exactly. Alternatively, manually download distribution to ~/.gradle/wrapper/dists corresponding directory.

3.5 Pre-compilation: Official Mandatory Step (Where 90% Get Stuck)

Root directory has import-into-idea.md with official 4-step minimal process:

1. Precompile spring-oxm with ./gradlew :spring-oxm:compileTestJava
2. Import into IntelliJ (File -> New -> Project from Existing Sources -> select build.gradle)
3. When prompted exclude the spring-aspects module
4. Code away

Step 1 is pre-compilation, not optional :

./gradlew :spring-oxm:compileTestJava
# Official also recommends pre-compiling spring-core
./gradlew :spring-core:compileTestJava

Windows users: use gradlew.bat ..., do NOT copy ./ (shell syntax). First run downloads dependencies, 5-20 minutes normal.

Interview favorite: Why pre-compile these? Two reasons:

Reason 1: RepackJar repackages artifacts. spring-core relocates third-party libraries into its own jar — for zero external dependencies, avoiding version conflicts. E.g., com.palantir.javapoet → org.springframework.javapoet (for AOT codegen), org.objenesis → org.springframework.objenesis (for instantiation), ASM, Kotlin reflection similarly. These artifacts only generated at build time ; IDEA indexing can't understand "dynamically generated" classes — without pre-compile, red errors everywhere, can't jump to definition. Reason 2: XJC generates source. spring-oxm test code depends on JAXB types generated by XJC from XSD at build time; these classes don't exist on first import.

Corresponding build scripts (7.0.8 excerpts):

// spring-core/spring-core.gradle
plugins {
    id 'org.springframework.build.multiReleaseJar'
}
// spring-core uses Multi-Release Jar for Java 21/24 features
multiRelease {
    releaseVersions 21, 24
}
// Relocate com.palantir.javapoet to org.springframework.javapoet and repackage
tasks.register('javapoetRepackJar', ShadowJar) {
    archiveBaseName = 'spring-javapoet-repack'
    configurations = [javaPoetConfig]
    relocate('com.palantir.javapoet', 'org.springframework.javapoet')
}
// Similarly relocate org.objenesis to org.springframework.objenesis
tasks.register('objenesisRepackJar', ShadowJar) {
    archiveBaseName = 'spring-objenesis-repack'
    relocate('org.objenesis', 'org.springframework.objenesis')
}
// spring-oxm/spring-oxm.gradle
xjc {
    xsdDir.set(layout.projectDirectory.dir("src/test/schema"))
    defaultPackage.set('org.springframework.oxm.jaxb.test')
}
// XJC generated sources only attached to test source set
sourceSets.test.java.srcDir(tasks.named("xjc", XjcTask).flatMap { it.outputJavaDir })
Hidden Pitfall: After IDEA Rebuild Project, generated sources may be cleaned, causing sudden "cannot find symbol" — just re-run pre-compile commands to restore.

To install compiled jars to local Maven repo for business projects:

# Official full build (slow)
./gradlew build
# Compile only, skip tests and checks (recommended for beginners)
./gradlew build -x test -x check
# publishToMavenLocal shorthand, -PskipDocs skips javadoc and zip distribution
./gradlew pTML -PskipDocs

Single-module iteration faster:

# Only compile and test spring-webmvc, -a skips rebuilding other modules, much faster
./gradlew -a :spring-webmvc:test

Gradle incremental build works well; don't habitually clean.

3.6 IDEA Import: Three Settings + One Exclusion

File -> Open (or New -> Project from Existing Sources)
-> Select spring-framework root build.gradle -> Open as Project / Trust Project

Select build.gradle, not just directory , so IDEA recognizes as Gradle project not plain directory.

When import dialog prompts, directly exclude spring-aspects module . If missed, fix later: File -> Project Structure -> Modules -> select spring-aspects -> click "-" to remove.

Why exclude? Module contains .aj files requiring AspectJ compiler (AJDT) which IDEA doesn't recognize by default (JetBrains known issue IDEA-64446), import guaranteed red. And it doesn't affect IoC/AOP mainline reading — Spring's own AOP core is in spring-aop, not spring-aspects.

Then verify these settings:

Project SDK : File -> Project Structure -> Project → JDK 25 (or 17)

Gradle Source : Settings -> Build Tools -> Gradle → Use Gradle from: 'gradle-wrapper.properties' (critical! Not local Gradle)

Gradle JVM : Same → Match Project SDK

Gradle user home : Same → Point to short path, no Chinese/no spaces cache directory

Build and run using / Run tests using : Same → Change to IntelliJ IDEA (debug breakpoints more stable, strongly recommended)

Annotation Processing : Settings -> Build -> Compiler → ✅ Enable, some modules depend on annotation processors

VM Options : Help -> Edit Custom VM Options → -Xmx4096m -Dfile.encoding=UTF-8

Two viable Gradle JVM postures (both verified):

Posture 1 (simple): Project SDK and Gradle JVM both JDK 25. Wrapper's Gradle 9.5.1 fully supports.

Posture 2 (more stable): Gradle JVM uses JDK 17, JAVA_HOME points to 17, let Gradle toolchain auto-download JDK 25 when needed (e.g., building Javadoc). If JDK 25 test runs hit weird module-system issues, switch to this.

Source includes .sdkmanrc (pins java=25); SDKMAN users run sdk env to switch terminal JDK.

First sync downloads dependencies, be patient. If stuck, first run ./gradlew tasks in command line to verify build health , then troubleshoot IDE — quickly distinguishes "network issue" vs "IDE issue".

Import success verification: Find spring-context module's AbstractApplicationContext, normal indexing/jump means success.

Build Your Own Debug Module: Decides If You'll Persist

Don't read source in Spring's test classes — too scattered, heavy context. Create minimal Demo module, new container yourself, breakpoint anywhere.

① Create my-debug/ at root, write my-debug.gradle:

plugins { id 'java-library' }

dependencies {
    api(project(":spring-context"))  // Transitive: beans + core + expression
    api(project(":spring-aop"))
    testImplementation platform('org.junit:junit-bom:6.0')
    testImplementation 'org.junit.jupiter:junit-jupiter'
}

② Register in settings.gradle:

include 'my-debug'

③ Minimal breakpoint-ready launcher:

package com.example;

import org.springframework.context.annotation.*;

@Configuration
@ComponentScan("com.example")
public class DemoApp {

    public static void main(String[] args) {
        // Breakpoint here, F7 step into = entire Spring universe
        var ctx = new AnnotationConfigApplicationContext(DemoApp.class);

        UserService service = ctx.getBean(UserService.class);
        System.out.println(service.hello("Spring 7"));

        ctx.close();
    }
}

@Component
class UserService {
    public String hello(String name) { return "Hello, " + name; }
}

④ Right-click Run/Debug.

First run triggers full indexing, wait for progress bar; thereafter instant.

After running, console prints Bean result — environment fully working. Can even check BeanFactory implementation:

System.out.println("BeanFactory implementation: " + ctx.getBeanFactory().getClass().getSimpleName());
// Output: DefaultListableBeanFactory

Advanced Verification: Use 7.0 New Feature BeanRegistrar for Triple Win

Spring 7's BeanRegistrar programmatic Bean registration perfect for "advanced verification" — simultaneously verifies: ① JDK version correct; ② Build artifacts correct (can load spring-context); ③ You can breakpoint step into BeanRegistry implementation — the exact starting point for source reading.

// One method does "batch register Beans by config"
public class LibraryRegistrar implements BeanRegistrar {
    @Override
    public void register(BeanRegistry registry, Environment env) {
        String[] branches = env.getProperty("library.branches", String[].class, new String[0]);
        for (String branch : branches) {  // library.branches=north,south
            registry.registerBean(
                branch + "Desk",  // northDesk / southDesk
                HelpDesk.class,
                spec -> spec.supplier(ctx -> new HelpDesk(branch))
            );
        }
    }
}

@Configuration(proxyBeanMethods = false)
@Import(LibraryRegistrar.class)  // Must use @Import to activate Registrar
class LibraryConfig { }
public class DebugSpring {
    public static void main(String[] args) {
        try (var context = new AnnotationConfigApplicationContext(LibraryConfig.class)) {
            // Breakpoint here, F7 into
            HelpDesk desk = context.getBean("northDesk", HelpDesk.class);
            System.out.println(desk);
        }
    }
}
Technical Highlight: BeanRegistrar uses if/for for conditional + batch registration, supports spec.prototype().lazyInit().supplier(...) chaining, 10x cleaner than BeanDefinitionRegistryPostProcessor — the shortest path to learning BeanDefinition registration. Two notes: Must use @Import to引入 (@Bean/@Component won't trigger); it replaces some @Conditional + @Configuration scenarios.

Don't Want Full Repo Compile? Lightweight Alternatives

Option A: Composite build. In your project's settings.gradle add includeBuild("../spring-framework"), directly substitute source for jars at runtime, breakpoints seamless.

Option B: BOM + sources jar. Use Spring BOM for dependencies, attach sources jar, debug into source from your own Demo.

Module Map: Don't Dive Into 9000 Files Blindly

Spring Framework has ~9000 Java source files ; absolutely cannot start from first file. Good news: Spring's module dependencies strictly layered, lower layers never depend on upper — engineering discipline maintaining zero circular dependencies.

Directory structure:

spring-framework/
├── build.gradle              # Root build (repos, global convention plugins)
├── settings.gradle             # Module list + plugin repos
├── gradle.properties           # Versions, JVM args
├── import-into-idea.md         # Your official manual
├── buildSrc/                   # Custom Gradle plugins (compile conventions, publish logic)
├── spring-core/                # Bottom: utilities, Resource, type system, annotation parsing
├── spring-beans/               # BeanDefinition, BeanFactory, property editors
├── spring-context/             # ApplicationContext, events, i18n, @Import
├── spring-aop/                 # ProxyFactory, Advisor, CglibAopProxy
├── spring-expression/          # SpEL
├── spring-jdbc/                # JdbcTemplate, DataSourceTransactionManager
├── spring-tx/                  # Transaction abstraction (PlatformTransactionManager)
├── spring-web / spring-webmvc/ # MVC mainline: DispatcherServlet, HandlerMapping
├── spring-webflux/             # Reactive
├── spring-test/                # TestContext, @SpringJUnitConfig
└── spring-oxm / spring-jms ... # Peripheral integrations

Core dependency chain (remember this graph):

Module dependency graph
Module dependency graph

Suggested Reading Order: spring-core → spring-beans → spring-context → spring-aop — master these four layers, Web and Data become natural.

Why this order? Because spring-beans' BeanFactory is IoC container heart, but depends on spring-core's Resource and ClassUtils; spring-context's ApplicationContext enhances BeanFactory with events, i18n, annotation-driven; spring-aop builds on Bean post-processor mechanism. Each layer naturally extends previous layer's capabilities — sequential reading prevents getting lost.

Mnemonic: core = foundation, beans = create Beans, context = manages whole family, rest = plugins attached on top.

Iron Law: Read source from spring-core upward, NEVER from spring-webmvc downward. Former is skeleton, latter is skin.

Interview follow-up: How to view inter-module dependencies? Check settings.gradle's include list, plus each module's build.gradle api project(':spring-core') declarations, combined with IDEA's Gradle view — clear at a glance.

Reading Methodology: One Question, One Breakpoint, One Call Chain

Spring millions of lines, aimless reading = suicidal learning . Dry reading = wasted. Here's a directly copyable method.

6.1 Three-Layer Funnel Method (This Article's Soul)

Three-layer funnel diagram
Three-layer funnel diagram

6.2 Breakpoint-Driven Method (Most Recommended)

Core philosophy: "One question, one breakpoint, one call chain" . Don't "read" source, "query" source.

Example: Want to understand "when does @Autowired injection complete?" Set breakpoints in DefaultListableBeanFactory#doResolveDependency and AutowiredAnnotationBeanPostProcessor#postProcessProperties, F7 step through, call chain emerges naturally.

Three advantages of this method: Has anchor . You're not randomly flipping files, but from "known entry" following call chain down. Variables window at breakpoint hit is more intuitive than any docs. While debugging, watch three things:

Call Stack (Frames): See which layer invoked this method, understand module collaboration — 10x faster than reading code.

Key Variables: beanName, beanDefinition, candidate — directly tell you which bean container is processing.

Conditional Breakpoints: When too many beans, add condition like beanName.equals("userService") or beanName.contains("Controller") to focus only on your bean, avoid drowning in hundreds of internal beans.

Two more power tools:

Evaluate Expression (Alt+F8): Execute expressions at breakpoint, live inspect beanDefinitionMap, singletonObjects contents.

Call Hierarchy (Ctrl+Alt+H): View call hierarchy, 10x more efficient than manual jumping; IDEA also right-click class -> Diagrams -> Show Diagram for instant inheritance graph.

6.3 Three Other Methods, Combine Usage

Interface Abstraction Method: Spring heavily uses Strategy pattern; first read top-level interface contract, then core implementation. E.g., learn BeanFactory: first memorize interface's 5 core methods, then examine DefaultListableBeanFactory concrete implementation.

Test-Driven Method: Spring's own test classes are best textbooks. E.g., search AnnotationConfigApplicationContextTests, run, breakpoint, observe call stack. Entering from tests often lighter than from main .

Git Archaeology Method: git blame to see why a line was written; git log --follow <file> for file evolution; git log -p -S "getBean" to see how a capability grew — 10x faster than static reading.

6.4 Breakpoint Map: Only Watch These Landing Points

How does container start? → AbstractApplicationContext#refresh() → Master scheduler , entire mainline directory

How is Bean created? → AbstractAutowireCapableBeanFactory#doCreateBean → Instantiation → property population → initialization full chain

Constructor inference & instantiation → AbstractAutowireCapableBeanFactory#createBeanInstance → Instantiation strategies

How are singletons batch instantiated? → DefaultListableBeanFactory#preInstantiateSingletons → Loop over BeanDefinition main flow

Get Bean / Circular dependency → AbstractBeanFactory#doGetBean, DefaultSingletonBeanRegistry#getSingleton → Singleton cache, three-level cache, FactoryBean, scopes

How do annotations become BeanDefinition? → AnnotatedBeanDefinitionReader, AnnotationConfigApplicationContext constructor chain → Config class parsing entry

How is AOP proxy generated? → AopProxyFactory -> CglibAopProxy → Proxy object "conjured" process

How does @Transactional work? → TransactionInterceptor#invoke() → Transaction true entry

How does HTTP request find method? → DispatcherServlet#doDispatch() → HandlerMapping -> Adapter full process

How is expression parsed? → SpelExpressionParser#parseExpression() → SpEL parsing execution

WebFlux folks remember to enable Async Stack Trace , else reactive chain stack traces are broken.

6.5 Reading Discipline & Execution Rhythm

Four Hard Rules:

One question per session. E.g., today only solve "how circular dependency broken", skip all other branches.

Write while reading, no pen = no read. Notes fixed three columns: Question -> Key Class/Method -> My Conclusion (one sentence). Can't draw sequence diagram = didn't understand.

Change one line to verify hypothesis. Flip allowCircularReferences to false, watch error — remembers better than reading code ten times.

Allow skipping. refresh() first 3 steps are setup, step 9 onRefresh() empty in parent, don't waste time; encounter *Utils/*Helper only read signature and javadoc, not implementation, unless error points there.

Landmines to Avoid:

🚫 Don't start from main line-by-line — Spring call chains too deep, read into existential crisis.

🚫 Don't get stuck in *Tests, *.aj (AspectJ files) — tests and aspect declarations aren't mainline.

✅ When encountering unfamiliar class, read javadoc first — Spring's javadoc is extremely thorough.

Directly Copyable Execution Rhythm:

Day 1: Setup env + run Demo + breakpoint in refresh() watch 12 steps → One hand-drawn call sequence diagram

Day 2-3: Trace Bean definition parsing -> registration -> instantiation -> initialization full chain → One note with stack traces

Day 4-5: Trace AOP: @EnableAspectJAutoProxy -> Advisor collection -> proxy creation → One self-written proxy Demo

Day 6+: Transactions, MVC dispatch, extension points (BFPP/BPP) → One "what can I do with this extension point" example each

This series will subsequently dissect refresh() 12 steps, three-level cache, AOP proxy — follow me, don't get lost , see next update first.

6.6 Get Familiar First: Core Call Chain

This chain is Spring IoC's "main artery", will be broken down step by step later; here establish overall impression:

Core call chain diagram
Core call chain diagram

How to find entry? From new AnnotationConfigApplicationContext(...) trace: constructor registers config classes (AnnotatedBeanDefinitionReader#register), then calls refresh() — everything starts here. Spring Boot scenario: SpringApplication.run -> refreshContext -> refresh(), different paths same destination.

refresh() 12 Steps: Grab This Master Map First

Though next article's main topic, prep article must let you recognize it — 90% of container interview questions hang on this mainline .

Below is 7.0.8 real source (simplified comments):

// org.springframework.context.support.AbstractApplicationContext (7.0.8)
@Override
public void refresh() throws BeansException, IllegalStateException {
    this.startupShutdownLock.lock();  // 7.x: evolved from synchronized to ReentrantLock
    try {
        this.startupShutdownThread = Thread.currentThread();
        StartupStep contextRefresh = this.applicationStartup.start("spring.context.refresh");

        // 1. Pre-refresh: set startup time, active flag, clear caches
        prepareRefresh();

        // 2. Tell subclass to refresh internal BeanFactory (returns DefaultListableBeanFactory)
        ConfigurableListableBeanFactory beanFactory = obtainFreshBeanFactory();

        // 3. Pre-process BeanFactory: inject ClassLoader, standard post-processors
        prepareBeanFactory(beanFactory);

        try {
            // 4. Allow subclass post-process after BeanFactory ready (parent empty, extension hook)
            postProcessBeanFactory(beanFactory);

            StartupStep beanPostProcess = this.applicationStartup.start("spring.context.beans.post-process");
            // 5. Execute BeanFactoryPostProcessor — parse config classes, scan Beans, register BeanDefinition ★
            invokeBeanFactoryPostProcessors(beanFactory);
            // 6. Register BeanPostProcessor — AOP, @Autowired's behind-the-scenes ★
            registerBeanPostProcessors(beanFactory);
            beanPostProcess.end();

            // 7. Initialize i18n MessageSource
            initMessageSource();
            // 8. Initialize event broadcaster
            initApplicationEventMulticaster();
            // 9. Subclass extension hook (Spring MVC/Boot create Web container here)
            onRefresh();
            // 10. Register event listeners
            registerListeners();
            // 11. Instantiate all non-lazy singletons ★★ Where singleton Beans truly born
            finishBeanFactoryInitialization(beanFactory);
            // 12. Cleanup: publish ContextRefreshedEvent, start Lifecycle Beans
            finishRefresh();
        } catch (RuntimeException | Error ex) {
            // Fail = rollback: stop started Lifecycle Beans, destroy created singletons, reset active flag
            if (this.lifecycleProcessor != null && this.lifecycleProcessor.isRunning()) {
                this.lifecycleProcessor.stop();
            }
            destroyBeans();
            cancelRefresh(ex);
            throw ex;
        } finally {
            contextRefresh.end();
        }
    } finally {
        this.startupShutdownThread = null;
        this.startupShutdownLock.unlock();
    }
}
refresh() 12 steps visual
refresh() 12 steps visual

Three Most Critical Steps, Remember via House-Building Analogy:

⑤ invokeBeanFactoryPostProcessors = Collect Blueprints : .class -> BeanDefinition, only register not new. Config class parsing, @ComponentScan, @Import all here.

⑥ registerBeanPostProcessors = Install Hooks : Register in PriorityOrdered > Ordered > normal order; AOP proxy creator and @Autowired injector buried here.

⑪ finishBeanFactoryInitialization = Build House : Non-lazy singletons all instantiated; circular dependency, three-level cache, AOP proxy's "beam switching" all happen here.

First 3 steps are setup, step 9 parent empty — don't waste time.

One-Sentence Summary: refresh() is NOT the method that creates singleton Beans; it's the "orchestration method preparing container from 0 to ready" . Singleton Bean mass instantiation only occurs at step 11, but all prep work (BeanDefinition, post-processors) completed beforehand.

Two Interview-Worthy Details:

Detail 1: Lock Evolution. Old version used synchronized (this.startupShutdownMonitor), 7.x upgraded to ReentrantLock (private final Lock startupShutdownLock = new ReentrantLock()), finer concurrency control, supports tryLock timeout to judge if container refreshing. Many online tutorials still show old code — watch for this when comparing. Detail 2: Template Method Pattern. refresh() fixes container startup main flow, but postProcessBeanFactory(), onRefresh() hooks left for subclasses — main flow fixed, details delegated to subclasses . This design pattern scores high in interviews.

Why start from refresh() not getBean()? Because refresh() is container lifecycle chronicle, getBean() just one link; panorama first then details, minimal cognitive load.

After running, you'll see in call stack: refresh() -> obtainFreshBeanFactory() -> invokeBeanFactoryPostProcessors() -> finishBeanFactoryInitialization() — the complete container startup skeleton. Runnable debug test class (note 7.0 removed javax.annotation support, @PostConstruct must use jakarta.annotation package):

// Place in spring-context test directory to run
public class BeanLifecycleDebugTest {
    @org.junit.jupiter.api.Test
    void debugRefresh() {
        // Breakpoint at AbstractApplicationContext#refresh() first line
        var ctx = new org.springframework.context.annotation.AnnotationConfigApplicationContext(Config.class);
        System.out.println(ctx.getBean(MyBean.class));
    }
    static class Config {
        @org.springframework.context.annotation.Bean
        MyBean myBean() { return new MyBean(); }
    }
    static class MyBean {
        @jakarta.annotation.PostConstruct  // 7.0 removed javax.annotation support
        void init() { System.out.println("MyBean init"); }
    }
}

Troubleshooting Cheat Sheet: 90% Failures = "Version Misaligned + No Pre-compile"

Merged/deduped pits from 8 sources into this table, recommend bookmark:

1. Gradle distribution/dependency download extremely slow or fails → Official sources overseas → init.gradle inject Aliyun mirror; distribution URL to Tencent mirror; --refresh-dependencies clear cache retry; manual download to ~/.gradle/wrapper/dists

2. Import shows red everywhere, can't jump to definition → RepackJar/XJC artifacts generated at build time, IDE index missing → First ./gradlew :spring-oxm:compileTestJava and :spring-core:compileTestJava then import; after File -> Invalidate Caches

3. Cannot find org.springframework.objenesis.* / javapoet classes → Same, repackaged artifacts not generated → Same, pre-compile spring-core

4. spring-oxm test classes many "cannot find symbol" → JAXB/XJC generated sources missing → ./gradlew :spring-oxm:compileTestJava; Rebuild Project then re-run pre-compile

5. spring-aspects compile fails, red everywhere → AspectJ compile-time weaving, IDEA doesn't recognize (IDEA-64446) → Exclude module at import, or install AspectJ Support plugin; doesn't affect mainline reading

6. Unsupported class file major version / major version 69 → Gradle/JDK version mismatch; 8.x can't run JDK 25 → Project SDK and Gradle JVM both 17+ (recommend 25); Gradle use Wrapper's 9.5.1, strictly forbid JDK 11 and below

7. Build reports toolchain can't find JDK 25 → Build toolchain needs 25 → JAVA_HOME point to 17/25, let Gradle auto-download JDK 25 toolchain

8. Cannot find jakarta.* classes / javax.* invalid → 7.0 fully removed javax.*, Jakarta EE 11 hard baseline → Fully switch to jakarta.*; verify dependencies are 7.0.8 versions

9. spring-jcl resolution fails → Module deleted → Use Commons Logging 1.3.0, skip old article operations

10. Source change won't compile, @Nullable errors → NullAway validating null-safety annotation consistency → This is 7.0's JSpecify validation mechanism, add annotations per hints

11. Compile extremely slow, OOM, Daemon hangs → Full compile + insufficient memory → org.gradle.jvmargs=-Xmx4g; enable parallel/caching/daemon; compile only needed modules; source on SSD, pure English short path; disable antivirus real-time scan on first sync

12. IDEA indexing hangs, memory spikes → Too many modules, heap insufficient → Increase IDEA heap (-Xmx4g); exclude irrelevant modules, only import core

13. Tests fail massively → Environment-dependent failures (JMX, DB, scheduled tasks) → Reading source doesn't need full tests, build with -x test; unit tests use ./gradlew :module:test --tests xxx , IDE run not fully compatible

14. Breakpoint jumps around, line numbers mismatch, jumps into decompiled class → Gradle compile vs debug mismatch / source vs artifact inconsistency → Build and run using -> IntelliJ IDEA; first ./gradlew :spring-context:classes compile once; confirm using project modules not External Libraries

15. Chinese comments garbled → Encoding inconsistency → IDEA settings all File Encodings to UTF-8

16. Various weird path errors → Source in Chinese/spaced path → Move to pure English, no spaces, short path like D:/code/spring-framework

17. 7.0.8 new APIs no online resources → Version too new, blogs still 5.x → Only trust three sources : source Javadoc, spring-framework/docs, GitHub Issues/PR; old blogs for ideas only, don't copy code

Troubleshooting Golden Rule: 90% failures are "version misaligned + no pre-compile". Suspect these two first, then question life. Compile issues troubleshoot in order: JDK version -> Network repos -> Memory params — almost never goes wrong.

Interview Rapid-Fire: Memorize These for Bonus Points

Q1: Why compile Spring source yourself? GitHub reading not enough? Only after compile can you breakpoint, modify code, see immediate effect — most efficient way to understand IoC/AOP runtime; locally compilable source is strongest debugging tool for framework-level production issues.

Q2: Why Gradle not Maven? Multi-module build (20+ submodules), custom build logic (buildSrc convention plugins, RepackJar repackaging), build cache & incremental compile more efficient. Maven relies on plugins, Gradle on code — flexibility difference of an order of magnitude.

Q3: Why emphasize Wrapper over local Gradle install? Large multi-module projects like Spring are highly sensitive to Gradle version; once global version diverges from gradle-wrapper.properties, weird dependency resolution and incremental compile issues appear. Wrapper guarantees 100% alignment — engineering best practice.

Q4: Why must pre-compile spring-oxm/spring-core before import? Two reasons: 1) spring-oxm depends on JAXB types generated by XJC from XSD at build time; 2) spring-core/spring-oxm have RepackJar tasks that relocate dependencies into jar. Both artifact types don't exist at first IDE import — without pre-compile, unresolvable.

Q5: Which refresh() steps most critical? Step 5 invokeBeanFactoryPostProcessors (parse config classes, scan/register BeanDefinition), Step 6 registerBeanPostProcessors (register post-processors, AOP and @Autowired rely on it), Step 11 finishBeanFactoryInitialization (singleton Beans truly born). First 3 steps setup, step 9 parent empty.

Q6: 7.x refresh() changes vs old versions? startupShutdownMonitor synchronization evolved from synchronized to ReentrantLock (startupShutdownLock), finer concurrency control, supports tryLock timeout to judge container refreshing.

Q7: Spring 7 biggest changes vs 6? Baseline: JDK 17 floor + embrace 25, Jakarta EE 11, JSpecify null-safety, Jackson 3 transition; Capabilities: Programmatic Bean registration (BeanRegistrar), Core Resilience (@Retryable default 3 retries/1s interval, annotation name matches Spring Retry, just change import to migrate), API Version Governance, JmsClient/RestTestClient, removed spring-jcl.

Q8: RestTemplate still usable? 7.0 usable but deprecated roadmap (7.1 @Deprecated, 8.0 removal); new code should use RestClient or HTTP Interface Client, migrate per client.

Q9: How confirm reading 7.0.8 behavior not 5.x/6.x memory? Use git log --follow <file> to see recent commits, cross-reference with release notes Breaking Changes.

Q10: How verify you truly understood? Three standards: Can draw call chain, can flip a switch to reproduce error, can implement a small feature using corresponding extension point (e.g., write a BeanPostProcessor adding proxy to all Beans).

30-Second Answer Template (memorizable):

I'd first lock Spring Framework 7.0.8, build with source-bundled Gradle Wrapper, JDK 17+ local recommend 25. Then pre-compile spring-core, spring-oxm, import excluding spring-aspects. Reading not from utilities but from minimal AnnotationConfigApplicationContext use case, breakpoint AbstractApplicationContext#refresh(), follow container init, BeanDefinition registration, Bean instantiation mainline. This ensures reading has entry, mainline, feedback.

This answer tells interviewer: You're not "pretended to read source", you actually know HOW to read.

Command Cheat Sheet + One-Page Self-Checklist

Command Cheat Sheet

# Clone specific version (shallow)
git clone --branch v7.0.8 --depth 1 https://github.com/spring-projects/spring-framework.git

# View wrapper-locked Gradle version
./gradlew --version
cat gradle/wrapper/gradle-wrapper.properties

# Pre-compile (MUST before IDEA import)
./gradlew :spring-oxm:compileTestJava
./gradlew :spring-core:compileTestJava

# Full build skipping tests
./gradlew build -x test -x check

# Compile only core three modules
./gradlew :spring-core:compileJava :spring-beans:compileJava :spring-context:compileJava -x test -x javadoc

# Single-module fast iteration
./gradlew -a :spring-webmvc:test

# Install to local Maven repo (local iteration)
./gradlew pTML -PskipDocs

One-Page Self-Checklist

[ ] JDK 17+ installed, java -version correct
[ ] git clone and checkout v7.0.8 (not main, not ZIP)
[ ] ./gradlew --version shows Gradle 9.x + JVM 17/25
[ ] ./gradlew :spring-oxm:compileTestJava  BUILD SUCCESSFUL
[ ] IDEA import build.gradle, Project SDK = 17/25
[ ] Gradle source = gradle-wrapper.properties, Build and run using = IntelliJ IDEA
[ ] spring-aspects excluded from Modules
[ ] Mirrors configured, dependencies no longer timeout
[ ] my-debug module Debug launches
[ ] Breakpoint hits refresh(), sees 12 steps
[ ] Notes template ready, first chain recorded

All checked? Congrats, environment chapter done — you've surpassed 80% who only bookmark but never act .

Closing Words

Prep chapter only needs five sentences:

Lock version first: Spring Framework 7.0.8, JDK 17 baseline, 25 recommended.

Build with Wrapper: Don't randomly install Gradle yourself.

Pre-compile before import: spring-oxm/spring-core, exclude spring-aspects.

Read via Demo: Minimal Demo + breakpoint refresh(), one question one breakpoint one call chain.

Grasp mainline entry: core -> beans -> context -> aop, refresh() is your first station.

Hardest part of reading Spring source isn't code itself, but the path from "open IDE" to "first breakpoint hit" . Today you paved that road; subsequent iterations much smoother. Recommend habitually sync, watch build.gradle and gradle-wrapper.properties changes.

Next Article Preview: We'll dive into refresh() 12 steps, focusing on three things — how config classes parsed in invokeBeanFactoryPostProcessors, real moment three-level cache resolves circular dependency (with intentional circular dependency Demo), and exactly which step AOP proxy "switches beams". Want first look, follow to not get lost .

References: Spring Framework 7.0 Release Notes, Official Build from Source Wiki and import-into-idea.md, v7.0.8 gradle-wrapper.properties, Spring Framework 7.0 GA Announcement, Spring Boot 4.0 GA Announcement
Original Source

Signed-in readers can open the original source through BestHub's protected redirect.

Sign in to view source
Republication Notice

This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactadmin@besthub.devand we will review it promptly.

DebuggingAOPSpring FrameworkIoC ContainerBean LifecycleJDK 17Pre-compilationGradle WrapperSource Code ReadingMulti-Release JARJSpecifyJDK 25Jakarta EE 11Spring 7.0.8IDEA Configurationrefresh methodRepackJarXJC
Reader feedback

How this landed with the community

Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.