跪拜 Guibai
← Back to the summary

Spring 7.0.8 Source Study: From Memorizing Answers to Modifying the Framework

Version baseline: Spring Framework 7.0.8 (released 2026-06-08, shipped with Spring Boot 4.1; 7.0 GA was released in November 2025, serving as the underlying framework for Spring Boot 4.x)

Runtime environment: JDK 17 minimum, officially recommending 21/25 LTS | Jakarta EE 11 (Servlet 6.1 / JPA 3.2) | Kotlin 2.2 | Gradle 9.x All class names, method names, and annotations in this article are verified against 7.0.8. Don’t use old maps to find new worlds.

When asked “How does Spring handle circular dependencies?” in an interview, 90% of people can recite the “three-level cache,” but a follow-up “Could you drop the second level?” leaves most speechless. This article doesn’t ask you to memorize new answers; it covers three things: why to read source code, where Spring leaves doors open, and how to plug your own code in. It’s for Java engineers who want to move from “using” to “modifying.”

1. At the interview: one question exposes the memorizer

Let me first reconstruct an interview I personally experienced (a synthesis of several real ones):

Interviewer: Your resume says you’re proficient in Spring. Why spend time reading Spring source code? Isn’t memorizing IoC and AOP enough?

Candidate A (memorizer): It works. IoC is inversion of control; Bean lifecycle is instantiation → property population → initialization → destruction; circular dependency relies on the three-level cache: singletonObjects, earlySingletonObjects, singletonFactories……

Interviewer: Good, but let me probe further. First, if AOP is turned off, is the two-level cache sufficient? Second, I want to insert custom logging logic before and after every bean initialization; which lines do you write? Third, the project needs to dynamically register beans based on the environment; do you use @Bean and pile up if statements?

Candidate A: …… (silence)

How does a source-code-savvy candidate answer?

Candidate B (source-code): Let me start with the conclusion. The two-level cache can indeed resolve pure circular dependencies, but the real reason Spring introduced the third level is the timing of AOP proxy objects. In doCreateBean(), when a circular reference occurs, getEarlyBeanReference() triggers SmartInstantiationAwareBeanPostProcessor early, ensuring that B injects A’s proxy rather than the raw object. Without the third level, in AOP scenarios B would inject a non-proxied bare object, and all aspects like transactions and logging would fail.

Interviewer (nodding): What about automatically logging the time spent on Service methods without AOP, using Spring’s own mechanisms?

Candidate B: Use BeanPostProcessor#postProcessAfterInitialization to wrap a proxy; more elegantly, use SmartInstantiationAwareBeanPostProcessor at the getEarlyBeanReference stage to handle circular dependency cases. In our project, we did exactly that, and it was super convenient for debugging slow endpoints after deployment. Later I noticed that Spring’s built-in AbstractAutoProxyCreator follows the same idea, so I read its source code as well.

One memorizes conclusions; the other describes structure. The interviewer’s internal OS: the salary offer differs by at least 30%.

Memorizer vs source-code: what differs

Look at the capability-tier diagram and see where you fit:

image.png

From framework user to framework contributor, each level up brings a salary tier up. Memorizers get stuck at L1; source-code readers can push to L2, L3.

Now compare across a table:

Dimension Only memorizing Reading source code
Problem problem Guess + search, lucky, slow Check stack trace, directly locate doCreateBean, pinpoint root cause
Feature extension Only call official APIs Custom extension points, tailor Spring’s native capabilities
Middleware wrapping Hard-code utility classes Elegant integration with ImportBeanDefinitionRegistrar
Performance optimization "Just change the connection pool" Know DefaultListableBeanFactory’s beanDefinitionMap is a ConcurrentHashMap, explain why Spring startup is slow
Architecture understanding Memorize scattered points Master design patterns and layered architecture thinking
Interview follow-up "And then... nothing" Can counter-output, turning the table on the interviewer

Summarize the four-level benefit of reading source code, from low to high: ① Use it better (stop blind configuration) → ② Explain why (the 6 causes of transaction failure can be derived from proxy mechanics) → ③ Self-heal in production (read stack traces) → ④ Extend Spring, make the framework work for you.

If the interviewer directly asks “why read source code,” the 30-second standard answer is three sentences:

I read source code to gain three things: a troubleshooting map (infer from the exception stack which step of refresh() failed), a checklist of extension points (know the official hooks like BeanPostProcessor, BeanFactoryPostProcessor, ImportSelector, and the new BeanRegistrar in Spring 7), and version judgment (JSpecify null safety, @Retryable, Class-File API; without understanding the underlying logic, you only copy configurations and don’t know why they break).

Three pain points of memorization

  1. Lost when asked for a scenario: You know definitions, but when a bean fails to create or a circular dependency exception appears, you rely on search-and-error;
  2. Cannot customize extensions: When business needs special bean management, you only write business code, no capability building on Spring;
  3. No interview moat: Everyone can recite IoC and AOP; you have no distinguishing factor.

In short: Memorization tells you “what,” source code tells you “why” and “how to change it.”

This article is a bit long; consider bookmarking it. The practical code in the second half is ready to use. Follow me; the next post will dissect refresh() line by line.

2. Why memorization is increasingly insufficient

2.1 Memorization gives conclusions, source code gives cause-effect chains

Memorization gives you a full stop: “The three-level cache solves circular dependencies.”

Ask three follow-up layers and you break:

  1. Why three levels, not two?
  2. Why must AOP-proxied objects be exposed early?
  3. Why can’t constructor injection circular dependencies be resolved?

Source code answers the cause. Here are two scenarios from my daily development:

Scenario 1: The frontend sends an array parameter, the backend receives it with @RequestParam List<String> ids, and an error occurs. A memorizer might only know “add @RequestParam.” But having read the source, you know RequestParamMethodArgumentResolver tries to convert collection types via ConversionService, and the problem lies in the separator of StringToCollectionConverter—simply configure a custom Converter to solve it, no need to search.

Scenario 2: A colleague’s @Async doesn’t work; you say in 30 seconds “self-invocation within the same class bypasses the proxy”; a transaction in production mysteriously fails; you pinpoint “self-call / private method / exception swallowed.”

Check this scenario comparison table to see the difference in daily life:

Scenario Only memorizing Actually reading source code
Bean not injected “Forgot to add @Component?” Check whether BeanDefinition is registered, whether AutowiredAnnotationBeanPostProcessor runs
AOP not working “Try adding @EnableAspectJAutoProxy” Determine whether the proxy was replaced, whether it’s a this call, whether BPP order is problematic
Circular dependency “Three-level cache” Locate getSingleton(), addSingletonFactory(), the timing of early exposure
Autowiring failure “Configuration not taking effect” Follow ImportSelector, Condition, BeanFactoryPostProcessor
Want to extend Change business code Use extension points to enhance the container non-invasively

This is the dividing line between “using” and “modifying.” Interviewers want people who can solve problems at the framework layer—business code anyone can write, but few can work at the frame level.

2.2 In the 7.0 era, a load of old memorized answers is obsolete

The version of source code you read determines your technical horizon:

image.png

If you still answer interviews with 5.x-era answers, the interviewer immediately knows you’re not keeping up. List of expired memorized answers:

Change point Old material Actual situation in Spring 7.0.8
Annotation namespace javax.annotation / javax.inject Removed, fully jakarta.*
Logging bridge spring-jcl provides Commons Logging API Removed, switched to Apache Commons Logging 1.3+
URL suffix matching /user.json automatically matches /user Removed, use content negotiation or explicit paths
Trailing slash /user and /user/ are equivalent No longer equivalent by default; use UrlHandlerFilter
Path matching AntPathMatcher is default Deprecated, default is PathPattern
Class file reading Slimmed ASM branch Java 24+ uses Class-File API (JEP 484)
Null safety Mixed annotations Unified JSpecify with @Nullable / @NonNull

2.3 Source-level new changes in Spring 7.0.8

Beyond the “expired,” the “new” matters. Several you must know:

1. Deep virtual thread integration

Spring 7.0 fully embraces Project Loom. The traditional “one request per platform thread” model is replaced by virtual threads—you can get async performance with synchronous-style code. At the source level, TaskExecutor and TaskScheduler now support virtual threads:

// application.properties
// spring.threads.virtual.enabled=true

@RestController
public class OrderController {
    @GetMapping("/order/{id}")
    public Order getOrder(@PathVariable Long id) {
        // This method runs on a virtual thread; blocking I/O no longer occupies a platform thread
        return orderService.findById(id);
    }
}

Controller code doesn’t change at all; underneath, it runs on virtual threads.

2. JSpecify full null safety

Spring 7.0 replaces custom null annotations with JSpecify annotations. Reading source, you’ll see many @Nullable, @NonNull. With IDE support, null-pointer risks are caught at compile time.

Here’s a trap: after upgrade, unannotated types default to non-null. If your own BeanPostProcessor parameters can be null, you must explicitly declare @Nullable, otherwise the IDE will complain heavily and passing null will cause an NPE—much stricter than before.

3. AOT and native images mature

In 7.0.8, the BeanFactory initialization path is split into runtime and compile-time branches. AotApplicationContextInitializer does a lot of reflection-related prep at compile time, cutting startup time from seconds to milliseconds. Spring 7.0 also detects and reports circular dependencies during AOT compilation, avoiding runtime surprises.

4. Built-in resilience and new registration entry

@Retryable / @ConcurrencyLimit, and BeanRegistrar—these two new weapons directly relate to “how to extend Spring.” We’ll cover them in the practice section.

If you still understand the framework via 5.x source code, you’re looking at an outdated design. 7.0.8’s source incorporates many cloud-native, high-concurrency refactors—these are the real bonus points for senior positions.

3. Source map: see the forest before the trees

Too many beginners dive straight into spring-webmvc and give up after three days. Look at the map first.

Spring Framework 7 is a layered modular structure: upper layers depend on lower layers, and lower layers never depend upward—this engineering discipline is the most useful navigation rule when reading source:

image.png

Key points:

The container is essentially an “object production line”

What you write:

@Service
public class OrderService {
}

In Spring’s eyes is not just a class but: BeanDefinition (blueprint) → Bean instance → possibly proxy → singleton in container.

image.png

This diagram is the article’s main thread. Every extension point we discuss later is a “slot” left on this production line.

4. refresh() in 12 steps: the master script of all source

If you remember one thing from this article, it’s AbstractApplicationContext#refresh(). The entire Spring container startup is these 12 steps; all extension points are “reserved” by these methods.

Skeleton code (simplified, omitting exception handling and StartupStep timing):

@Override
public void refresh() throws BeansException, IllegalStateException {
    synchronized (this.startupShutdownMonitor) {
        prepareRefresh();                                   // ① Prepare: record startup time, validate environment

        ConfigurableListableBeanFactory beanFactory = obtainFreshBeanFactory();  // ② Get a “clean” BeanFactory

        prepareBeanFactory(beanFactory);                    // ③ Assemble infrastructure: ClassLoader, SpEL, Aware exclusions

        postProcessBeanFactory(beanFactory);                // ④ Subclass hook (Web container adds scopes here)

        invokeBeanFactoryPostProcessors(beanFactory);       // ⑤ ★ Parse configuration classes, scan @Component, register BeanDefinition
        registerBeanPostProcessors(beanFactory);            // ⑥ ★ Register BeanPostProcessor in ordered fashion

        initMessageSource();                                // ⑦ Internationalization
        initApplicationEventMulticaster();                  // ⑧ Event multicaster
        onRefresh();                                        // ⑨ Subclass hook (Tomcat / Jetty starts here)
        registerListeners();                                // ⑩ Register listeners

        finishBeanFactoryInitialization(beanFactory);       // ⑪ ★★ Instantiate all non-lazy singletons (the true birthplace of beans)
        finishRefresh();                                    // ⑫ Publish ContextRefreshedEvent
    }
}

Memory mnemonic: ⑤ collect blueprints (BeanDefinition) → ⑥ install tools (post-processors) → ⑪ build according to blueprint (instantiate). To memorize all 12 steps: Prepare → get factory → configure factory → three hooks → initialize singletons → publish event.

Steps ⑤⑥⑪ are starred because all extension points ultimately fall into these three steps. If you can locate a production issue to a specific step, you’ve surpassed 80% of candidates.

Why can’t steps 5 and 6 be swapped?

This is a frequent follow-up. Look at key source snippets:

// Step ⑤: first execute BDRPP (higher priority), then ordinary BFPP in priority order
protected void invokeBeanFactoryPostProcessors(ConfigurableListableBeanFactory beanFactory) {
    PostProcessorRegistrationDelegate.invokeBeanDefinitionRegistryPostProcessors(
        beanFactory.getBeanDefinitionRegistry(), getBeanFactoryPostProcessors());
    PostProcessorRegistrationDelegate.invokeBeanFactoryPostProcessors(
        beanFactory, getBeanFactoryPostProcessors());
}

// Step ⑥: internally registers in order PriorityOrdered -> Ordered -> ordinary
protected void registerBeanPostProcessors(ConfigurableListableBeanFactory beanFactory) {
    PostProcessorRegistrationDelegate.registerBeanPostProcessors(beanFactory, this);
}

// Step ⑪: freeze configuration, then instantiate all remaining non-lazy singletons
protected void finishBeanFactoryInitialization(ConfigurableListableBeanFactory beanFactory) {
    beanFactory.freezeConfiguration();
    beanFactory.preInstantiateSingletons();
}

If BPPs were registered before BFPPs run, then BFPPs themselves would be intercepted by BPPs, leading to all sorts of odd behavior. So ⑤ must come before ⑥: first finalize the blueprint, then install the tools.

Match errors to stages

Errors in different stages look completely different; match by shape:

Stage Typical error Direction
⑤ Blueprint NoSuchBeanDefinitionException, ConflictingBeanDefinitionException, No qualifying bean Scan path, missing annotations, config class not parsed
⑥ Tools Not eligible for getting processed by all BeanPostProcessors... BPP depends on a bean not yet ready
⑪ Construction BeanCurrentlyInCreationException (circular), UnsatisfiedDependencyException Dependency injection, early exposure

How does an annotation become a BeanDefinition?

Another common question—when does a @Component-annotated class become a BeanDefinition? The chain:

image.png

As for @Autowired and @Value, they don’t participate in BeanDefinition parsing; AutowiredAnnotationBeanPostProcessor handles them during property injection in step ⑪. Don’t mix them up.

Interview bonus sentence: “The essence of Spring startup is the 12 steps of refresh(); all extension points are reserved by these methods.” This can be the opener for any follow-up.

5. Extension point panorama: Spring is a row of “slots”

Spring’s greatest strength isn’t IoC/AOP itself, but how it takes “open for extension, closed for modification” (OCP) to the extreme. The framework is a row of slots waiting for you to plug in.

Spring’s soul lies in extension points: there are 9 implementation classes of BeanPostProcessor alone, and 5 key implementations of BeanFactoryPostProcessor—reading source isn’t to memorize them, but to understand “where Spring leaves hooks.”

First, the panorama table (screenshot and save):

Extension point When it works What it can do Typical scenario Difficulty
ApplicationContextInitializer Before container refresh Initialize environment, register initial resources Startup prep ⭐
BeanDefinitionRegistryPostProcessor Registration phase of BeanDefinition Register entirely new beans ConfigurationClassPostProcessor scans annotations, MyBatis Mapper scan ⭐⭐⭐
BeanFactoryPostProcessor After definitions load, before instantiation Modify BeanDefinition attributes ${} placeholder parsing, dynamic config changes ⭐⭐
InstantiationAwareBeanPostProcessor Before/after instantiation Intercept creation, property injection Custom instantiation logic (e.g., Supplier) ⭐⭐⭐⭐
SmartInstantiationAwareBeanPostProcessor Instantiation phase Expose early references Circular dependency + AOP depends on it ⭐⭐⭐⭐
BeanPostProcessor Before/after initialization Wrap, replace, enhance beans AOP, @Async, @Transactional all rely on it ⭐⭐⭐
Aware interfaces During bean initialization Access container resources ApplicationContextAware, EnvironmentAware ⭐
FactoryBean When bean is retrieved Create complex objects MyBatis SqlSessionFactoryBean, Feign clients ⭐⭐
@Import + ImportBeanDefinitionRegistrar Config class parsing Batch-register beans from third-party frameworks @MapperScan, @EnableFeignClients ⭐⭐⭐
ImportSelector / DeferredImportSelector Config class parsing Conditionally import config classes Boot auto-configuration principle ⭐⭐⭐
ApplicationListener Event publishing Decouple business, listen for refresh Listen for ContextRefreshedEvent to warm up ⭐
SmartInitializingSingleton After all singletons initialized Preload, register routes, check Startup finishing ⭐⭐
BeanRegistrar (new in 7.0) During container refresh Programmatically batch-register beans with plain Java code Modular assembly, AOT friendly ⭐⭐⭐⭐
Custom Scope / BeanFactory Runtime Change the existence form of beans Tenant-level, thread-level scopes ⭐⭐⭐⭐⭐

Too many extension points? Categorize by intervention timing: load definition → instantiate → inject → initialize → ready. String the slots on a timeline and you’ll see at a glance:

image.png

The easiest to mix up: BFPP vs BPP

This is the most frequently asked follow-up. Remember this flow:

image.png

One sentence: BFPP modifies blueprints, BPP modifies finished products. One acts before born, the other around born. The orange nodes are the extension entries Spring leaves: after initialization completes, before returning to container, you can replace or proxy the bean—remember this spot, chapter 6 uses it.

Type Handles object Timing Action
BeanFactoryPostProcessor BeanDefinition (blueprint) Before bean instantiation Modify metadata
BeanPostProcessor Bean instance (product) Before/after initialization Enhance or replace object

Two more points, also common pitfalls:

In 7.0, BeanPostProcessor methods are all default, override as needed:

public interface BeanPostProcessor {
    default Object postProcessBeforeInitialization(Object bean, String beanName) { return bean; }
    default Object postProcessAfterInitialization(Object bean, String beanName) { return bean; }
}
// plus the InstantiationAwareBeanPostProcessor subinterface to intervene even earlier

Two source locations to memorize:

When multiple BPPs exist, who runs first?

Looking at source, execution is a for loop, but returning null mid-loop breaks it:

// AbstractAutowireCapableBeanFactory
public Object applyBeanPostProcessorsBeforeInitialization(Object existingBean, String beanName) {
    Object result = existingBean;
    for (BeanPostProcessor processor : getBeanPostProcessors()) {
        result = processor.postProcessBeforeInitialization(result, beanName);
        if (result == null) {
            return result;   // Key: returning null breaks subsequent processors
        }
    }
    return result;
}

Two ways to control order:

// Method 1: @Order (lower number = higher priority)
@Order(1)
@Component
public class FirstBPP implements BeanPostProcessor { ... }

// Method 2: implement PriorityOrdered (higher priority than @Order)
@Component
public class HighestPriorityBPP implements BeanPostProcessor, PriorityOrdered {
    @Override
    public int getOrder() {
        return Ordered.HIGHEST_PRECEDENCE;
    }
}

Interview bonus sentence: BeanPostProcessor is Spring’s “open bus”; about 90% of Spring’s advanced features—@Autowired injection, @Transactional proxy, @Async, @Retryable—are built on it. If you can write one, you work with the same mechanism as the Spring team.

Now we have the map. The code below runs on JDK 17 + Spring 7.0.8 (tested).

6. Hands-on: write your own extension point

6.1 BeanPostProcessor: non-invasive timing log

A common need: avoid writing this in every method:

long start = System.currentTimeMillis();
// business logic
long cost = System.currentTimeMillis() - start;

Instead: any class annotated @LogInvocation gets its method execution time printed automatically. This is a classic non-invasive extension—no AOP annotations, yet doing AOP work.

Step 1, define the annotation:

@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
public @interface LogInvocation {
}

Step 2, write the processor (production-grade):

@Component
public class LogInvocationBeanPostProcessor implements BeanPostProcessor, PriorityOrdered {

    private static final Log log = LogFactory.getLog(LogInvocationBeanPostProcessor.class);

    @Override
    public int getOrder() {
        return Ordered.LOWEST_PRECEDENCE;   // control execution order
    }

    @Override
    public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {

        // Highlight 1: if already an AOP proxy, avoid double wrapping
        if (AopUtils.isAopProxy(bean)) {
            return bean;
        }

        // Highlight 2: get the real target class, not CGLIB-enhanced class
        Class<?> targetClass = AopProxyUtils.ultimateTargetClass(bean);

        // Highlight 3: meta-annotation lookup, more reliable than isAnnotationPresent
        if (AnnotationUtils.findAnnotation(targetClass, LogInvocation.class) == null) {
            return bean;
        }

        Class<?>[] interfaces = ClassUtils.getAllInterfacesForClass(targetClass);
        if (interfaces.length == 0) {
            return bean;   // only handle beans with interfaces, simpler JDK dynamic proxy
        }

        return Proxy.newProxyInstance(
                targetClass.getClassLoader(),
                interfaces,
                (proxy, method, args) -> {
                    long start = System.nanoTime();
                    try {
                        Object result = method.invoke(bean, args);
                        long cost = Duration.ofNanos(System.nanoTime() - start).toMillis();
                        log.info(String.format("[LogInvocation] %s.%s cost=%dms",
                                targetClass.getSimpleName(), method.getName(), cost));
                        return result;
                    } catch (InvocationTargetException ex) {
                        Throwable cause = ex.getCause();
                        throw cause != null ? cause : ex;   // unwrap original exception
                    } catch (IllegalAccessException ex) {
                        throw new IllegalStateException("Method access failed", ex);
                    }
                });
    }
}

Step 3, use it in a business class:

public interface PayService {
    String pay(BigDecimal amount);
}

@LogInvocation
@Service
public class PayServiceImpl implements PayService {
    @Override
    public String pay(BigDecimal amount) {
        try {
            Thread.sleep(80);
        } catch (InterruptedException e) {
            Thread.currentThread().interrupt();
        }
        return "pay success: " + amount;
    }
}

After invocation, log output:

[LogInvocation] PayServiceImpl.pay cost=82ms

Four highlights in this code, worth savoring one by one:

  1. Use BeanPostProcessor instead of modifying business code—the container creates the bean, you insert a processor, return an enhanced bean; this is Spring’s most classic extension.
  2. Use AopProxyUtils.ultimateTargetClass(bean) instead of bean.getClass()—if the bean is CGLIB-enhanced, bean.getClass() returns something like PayServiceImpl$$SpringCGLIB$$0, and your custom annotation won’t be found.
  3. Use AnnotationUtils.findAnnotation instead of isAnnotationPresent—the former handles annotation inheritance, meta-annotations, etc., more robustly.
  4. Use AopUtils.isAopProxy to avoid double proxying—a bean might already be proxied for transactions, async, or caching. Without the check, you get proxy-over-proxy, longer call chains, unpredictable behavior, and painful debugging.

By the way, the before/after hooks can be used separately. For audit logs, print “Bean[xxx] about to initialize” in postProcessBeforeInitialization and bind audit context, then confirm in postProcessAfterInitialization. An @AuditLog component is a standard use. Timing granularity can be μs ((System.nanoTime() - t0) / 1000) or ms as needed.

What if the bean has no interface? JDK proxy won’t work; switch to CGLIB Enhancer, 5 lines:

// Define @CostLog annotation + CGLIB enhancement for beans without interfaces
@Component
public class CostLogBeanPostProcessor implements BeanPostProcessor {

    @Override
    public Object postProcessAfterInitialization(Object bean, String beanName) {
        if (bean.getClass().isAnnotationPresent(CostLog.class)) {
            Enhancer enhancer = new Enhancer();
            enhancer.setSuperclass(bean.getClass());
            enhancer.setCallback((MethodInterceptor) (obj, method, args, proxy) -> {
                long start = System.currentTimeMillis();
                Object result = proxy.invokeSuper(obj, args);
                System.out.printf("[%s] method cost: %dms%n",
                        method.getName(), System.currentTimeMillis() - start);
                return result;
            });
            return enhancer.create();
        }
        return bean;
    }
}

For filtering, you can use AnnotatedElementUtils.hasAnnotation to check for @Service, or filter by beanName prefix, but the AnnotationUtils.findAnnotation approach is most stable.

This is the value of reading source: you know where Spring leaves extension points, so you can implement generic capabilities in a few lines.

6.2 BeanFactoryPostProcessor: modify blueprints before instantiation

BeanPostProcessor handles bean instances, BeanFactoryPostProcessor handles BeanDefinition metadata.

For example, force all application-level beans to lazy-load, or mark xxl-prefixed beans as lazy to optimize startup:

@Component
public class LazyInitBeanFactoryPostProcessor implements BeanFactoryPostProcessor {

    @Override
    public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) throws BeansException {
        for (String beanName : beanFactory.getBeanDefinitionNames()) {
            BeanDefinition bd = beanFactory.getBeanDefinition(beanName);
            // Filter 1: by role, only application-level
            // Filter 2: by name prefix, e.g., beanName.startsWith("xxl")
            if (bd.getRole() == BeanDefinition.ROLE_APPLICATION && !bd.isLazyInit()) {
                bd.setLazyInit(true);
                System.out.println("Forced lazy init: " + beanName);
            }
        }
    }
}

The charm: the bean isn’t created yet; you modify its definition and the container builds according to your modified blueprint.

Don’t underestimate it: @Value placeholder resolution (PropertySourcesPlaceholderConfigurer), MyBatis MapperScannerConfigurer, @ConfigurationProperties binding—all this pattern.

6.3 BeanDefinitionRegistryPostProcessor: hand-write @MapperScan

Suppose you’re a middleware engineer needing a feature like MyBatis’ @MapperScan: scan all interfaces in a package annotated with @MyRpcClient and auto-register them as Spring beans.

Why use BeanDefinitionRegistryPostProcessor (BDRPP) instead of a normal BeanFactoryPostProcessor? Look at execution timing:

image.png

The key difference is timing: BDRPP’s postProcessBeanDefinitionRegistry() runs before all regular BFPP’s postProcessBeanFactory(). This means you can register entirely new bean definitions, not just modify existing ones—the core ability to “extend Spring.”

Core code:

/**
 * Custom RPC client scanner
 * Simulates MyBatis @MapperScan and Feign @EnableFeignClients
 */
public class MyRpcClientScanner implements
        BeanDefinitionRegistryPostProcessor,
        PriorityOrdered {

    private final String basePackage;

    public MyRpcClientScanner(String basePackage) {
        this.basePackage = basePackage;
    }

    @Override
    public void postProcessBeanDefinitionRegistry(BeanDefinitionRegistry registry) {
        // Use Spring's built-in ClassPathBeanDefinitionScanner
        ClassPathBeanDefinitionScanner scanner =
            new ClassPathBeanDefinitionScanner(registry, false);

        // Add custom filter: only scan interfaces with @MyRpcClient
        scanner.addIncludeFilter(new AnnotationTypeFilter(MyRpcClient.class));
        // Set bean name generator
        scanner.setBeanNameGenerator(new AnnotationBeanNameGenerator());

        int count = scanner.scan(basePackage);
        System.out.println("MyRpcClientScanner registered " + count + " RPC clients");
    }

    @Override
    public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) {
        // Optional: modify registered BeanDefinitions
        // e.g., set FactoryBean for all RPC clients
    }

    @Override
    public int getOrder() {
        // Priority: framework core > user custom
        return Ordered.LOWEST_PRECEDENCE - 100;
    }
}

Trigger with an annotation, the standard @EnableXxx pattern:

@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.TYPE)
@Import(MyRpcClientScannerRegistrar.class)
public @interface EnableMyRpcClients {
    String[] basePackages() default {};
}

public class MyRpcClientScannerRegistrar implements ImportBeanDefinitionRegistrar {
    @Override
    public void registerBeanDefinitions(
            AnnotationMetadata metadata, BeanDefinitionRegistry registry) {
        Map<String, Object> attrs = metadata
            .getAnnotationAttributes(EnableMyRpcClients.class.getName());
        String[] packages = (String[]) attrs.get("basePackages");
        for (String pkg : packages) {
            registry.registerBeanDefinition(
                pkg + ".MyRpcClientScanner",
                BeanDefinitionBuilder
                    .genericBeanDefinition(MyRpcClientScanner.class)
                    .addConstructorArgValue(pkg)
                    .getBeanDefinition());
        }
    }
}

Verify execution order via Debug: set breakpoint at postProcessBeanDefinitionRegistry, check call stack:

// AbstractApplicationContext.refresh()
//   → invokeBeanFactoryPostProcessors()
//     → PostProcessorRegistrationDelegate
//       → invokeBeanDefinitionRegistryPostProcessors()
//         → MyRpcClientScanner.postProcessBeanDefinitionRegistry()

This is why @MapperScan lets interfaces become injectable beans—not magic, but the Registrar “forging” bean definitions early in container startup. Before reading source, you could only recite “MyBatis black magic”; after, you can write it in 30 lines. MyBatis goes further by registering a MapperFactoryBean for each interface, generating proxies in getObject().

Also note: FactoryBean has dual identity; getBean("xxx") returns the product of getObject(), to get the factory itself use getBean("&xxx").

6.4 BeanRegistrar: first-class citizen in Spring 7

Previously, to register multiple beans in one @Bean method, or register conditionally by environment, you had to write BeanDefinitionRegistryPostProcessor, long and error-prone. The pain:

@Configuration
public class DaoConfiguration {
    // Pain 1: one @Bean method registers only one bean
    @Bean
    public UserDao userDao() {
        return new MySqlUserDao();  // how to switch to PgUserDao based on config?
    }
    // Pain 2: want 10 data sources? write 10 @Bean methods...
    // Pain 3: can't write if/else in @Bean for conditional registration
}

7.0 gives a first-class official solution: org.springframework.beans.factory.BeanRegistrar. Introduced by Sebastien Deleuze in Spring Framework 7.0, it’s parsed by ConfigurationClassParser for @Imported BeanRegistrar implementations, invoking their register method. Compared to older ImportBeanDefinitionRegistrar, the API is simpler, no manual GenericBeanDefinition stitching:

class MyBeanRegistrar implements BeanRegistrar {
    @Override
    public void register(BeanRegistry registry, Environment env) {
        // 1️⃣ simplest registration
        registry.registerBean("foo", Foo.class);

        // 2️⃣ with scope / lazy / supplier
        registry.registerBean("bar", Bar.class, spec -> spec
                .prototype()
                .lazyInit()
                .description("Custom description")
                .supplier(context -> new Bar(context.bean(Foo.class))));

        // 3️⃣ conditional registration with plain if/else—impossible with @Bean
        if (env.matchesProfiles("mysql")) {
            registry.registerBean(MySqlRepository.class);
        } else if (env.matchesProfiles("postgresql")) {
            registry.registerBean(PostgreSqlRepository.class);
        }

        // 4️⃣ for loop: dynamically register multiple routes
        for (String region : List.of("cn", "eu", "us")) {
            registry.registerBean(region + "Router", RegionRouter.class,
                    spec -> spec.supplier(ctx -> new RegionRouter(region)));
        }
    }
}

@Configuration
@Import(MyBeanRegistrar.class)   // import via @Import, don't make it a @Bean method return
class MyConfiguration {}

Three highlights, great for interviews:

But know the boundary: it’s not a universal “push objects into container at runtime” plugin, but a BeanDefinition registration mechanism during container refresh. Conditions should come from information known at startup (Profile, config, module list).

When to use it instead of @Bean? When the registration count is determined by config, needs loops, or the same interface switches implementations per environment—that’s when BeanRegistrar shines.

Spring 7.0.8 introduces a simpler BeanRegistrar on top of BDRPP, but BDRPP remains the foundation for understanding framework extension mechanisms—know both.

6.5 Official textbook: built-in resilience in 7.0

If you think all this is third-party play, look at how Spring extends itself.

Spring 7.0 builds retry and concurrency limiting directly into the core: org.springframework.core.retry provides RetryTemplate, spring-context provides annotations, zero external dependencies:

@Configuration
@EnableResilientMethods          // master switch
public class ResilienceConfig { }

@Service
public class OrderService {

    @Retryable(maxRetries = 3, delay = 200, multiplier = 2, jitter = 50,
               includes = RemoteException.class)   // bare use defaults to 3 retries, 1 sec interval
    public void createOrder(Order order) { /* remote call */ }

    @ConcurrencyLimit(limit = 10)   // max 10 concurrent, backed by JDK Semaphore, especially useful with virtual threads
    public void heavyTask() { /* ... */ }
}

The important part—the implementation classes are right there:

org/springframework/resilience/annotation/RetryAnnotationBeanPostProcessor.class
org/springframework/resilience/annotation/ConcurrencyLimitBeanPostProcessor.class

See? Two annotations, two BeanPostProcessors. Spring extends Spring using the same trick from section 6.1.

So the chain is: annotation → BeanPostProcessor scan → generate AOP proxy → MethodInterceptor intercepting calls. @Transactional, @Async, @Cacheable all follow the same pattern. That’s “read one, understand many.”

Pitfall (must memorize): @Retryable and @Transactional are proxy-based, so self-invocation within the same class won’t work, and methods can’t be private/final. This sentence shows you’ve read source, not memorized annotations.

6.6 ApplicationListener: decouple business with events

Spring’s event mechanism is publish-subscribe, backed by ApplicationEventMulticaster. For example, after order creation, send notification, deduct points, push to message queue—use events to decouple:

// 1. Define event
public class OrderCreatedEvent extends ApplicationEvent {
    private final String orderId;
    private final String userId;

    public OrderCreatedEvent(Object source, String orderId, String userId) {
        super(source);
        this.orderId = orderId;
        this.userId = userId;
    }
    // getters...
}

// 2. Publish event
@Service
public class OrderService {
    private final ApplicationEventPublisher publisher;

    public void createOrder(String orderId, String userId) {
        // business logic...
        publisher.publishEvent(new OrderCreatedEvent(this, orderId, userId));
    }
}

// 3. Listen (can add @Async for async execution)
@Component
public class NotificationListener {
    @Async
    @EventListener
    public void handleOrderCreated(OrderCreatedEvent event) {
        sendNotification(event.getUserId(), "Order created successfully");
    }
}

The main flow doesn’t know how many downstream consumers exist. This is the easiest extension point to start with.

6.7 Run it, see results in 5 minutes

Finally, put the BeanPostProcessor and BeanRegistrar into a complete Demo. This Demo does not depend on Spring Boot at all; it’s a pure Spring container—many people’s Spring knowledge is actually Boot auto-configuration knowledge; running the container without Boot is the first step to “extend Spring yourself.”

public static void main(String[] args) {
    // Pure Spring container, no Boot, no auto-config
    var ctx = new AnnotationConfigApplicationContext(AppConfig.class);

    GreetingService first = ctx.getBean("greetingService", GreetingService.class);
    System.out.println("Result: " + first.greet("Spring Framework 7.0.8"));

    GreetingService second = ctx.getBean("greetingService", GreetingService.class);
    System.out.println("Same instance? " + (first == second) + "  (prototype scope)");

    ctx.close();   // trigger destroy → full shutdown flow
}

@Configuration
@Import(ServiceBeanRegistrar.class)      // BeanRegistrar from 6.4 activates via @Import
static class AppConfig {
    @Bean
    static TimingBeanPostProcessor timingBeanPostProcessor() {  // note static
        return new TimingBeanPostProcessor();
    }
}

Compile & run (JDK 17+, with 7.0.8 official jars in libs/):

javac -encoding UTF-8 --release 17 -cp "libs/*" -d out src/demo/Demo.java
java  -Dfile.encoding=UTF-8 -cp "out:libs/*" demo.Demo

Real output:

[BPP-before] demo.AppConfig -> about to initialize
  [BPP-before] greetingService -> about to initialize
  [BPP-after] greetingService -> proxy woven
  [Timing] greet() = 1735715 ns
Result: Hello, Spring Framework 7.0.8
  [BPP-before] greetingService -> about to initialize
  [BPP-after] greetingService -> proxy woven
Same instance? false  (prototype scope)

Four things to learn from the output:

  1. Business code untouched, timing stats woven in—that’s the power of AOP-style extension;
  2. AppConfig also goes through BPP, but timingBeanPostProcessor itself does not—BPP doesn’t process itself or other BPPs, a classic source detail;
  3. The second getBean prints “BPP-before/after” again—prototype re-runs full lifecycle on each creation;
  4. Two instances are not the same, confirming BeanRegistrar’s spec.prototype() works.

Running beats just reading: once code runs, source has a picture.

7. Deep dive into the three-level cache: understand “lazy decision” once

With the foundation above, let’s receive the most frequently asked interview question.

Memorized version: Level 1 singletonObjects (finished products), Level 2 earlySingletonObjects (semi-finished), Level 3 singletonFactories (factories).

Source version, look at three maps (DefaultSingletonBeanRegistry, 7.0.8):

/** Level-1 cache: complete singleton beans (finished) */
private final Map<String, Object> singletonObjects = new ConcurrentHashMap<>(256);
/** Level-2 cache: early references (already taken by someone else) */
private final Map<String, Object> earlySingletonObjects = new ConcurrentHashMap<>(16);
/** Level-3 cache: ObjectFactory factory—key is here */
private final Map<String, ObjectFactory<?>> singletonFactories = new HashMap<>(16);

Core retrieval logic (simplified):

protected Object getSingleton(String beanName, boolean allowEarlyReference) {
    Object singleton = this.singletonObjects.get(beanName);
    if (singleton == null && isSingletonCurrentlyInCreation(beanName)) {
        singleton = this.earlySingletonObjects.get(beanName);
        if (singleton == null && allowEarlyReference) {
            synchronized (this.singletonObjects) {
                singleton = this.singletonObjects.get(beanName);
                if (singleton == null) {
                    singleton = this.earlySingletonObjects.get(beanName);
                    if (singleton == null) {
                        ObjectFactory<?> factory = this.singletonFactories.get(beanName);
                        if (factory != null) {
                            singleton = factory.getObject();   // ⭐ lazy execution, may create AOP proxy
                            this.earlySingletonObjects.put(beanName, singleton);
                            this.singletonFactories.remove(beanName);
                        }
                    }
                }
            }
        }
    }
    return singleton;
}

The line that puts it in is more clever, in AbstractAutowireCapableBeanFactory#doCreateBean:

boolean earlySingletonExposure = (mbd.isSingleton() && this.allowCircularReferences
        && isSingletonCurrentlyInCreation(beanName));
if (earlySingletonExposure) {
    // Note: what’s stored is not the object, but a “factory that can produce an early object”
    addSingletonFactory(beanName, () -> getEarlyBeanReference(beanName, mbd, bean));
}

getEarlyBeanReference calls SmartInstantiationAwareBeanPostProcessor; AOP proxy is woven in right here.

Sequence diagram:

image.png

Why must it be three levels?

Level 3 stores a factory, not an object, to defer the decision—only when a circular reference truly occurs does it execute the factory, generating an early reference that might be a proxy.

Without AOP: factory returns original object → put into level-2 cache; With AOP: factory returns proxy → ensures B injects A’s proxy, not raw object.

Can level 2 be removed? Not easily: level-2 cache ensures the same early reference is created only once (idempotent under concurrency/multiple circular references), and level-3 factory is deleted after use. With only two levels, all beans would create proxies early, breaking performance and correctness.

This is why interviewers ask about “three levels”—they test your understanding of the intent behind lazy execution in getEarlyBeanReference.

Three bonus points:

If circular dependencies confuse you, my crude method is to hand-draw three diagrams: normal creation flow, singleton pool changes, A→B→A circular sequence, and manually trace getSingleton’s three-level logic. One pass and it clicks.

8. AOP proxy: where exactly is it woven?

Another common misconception: many think the proxy is created at the start of getBean(). Wrong. postProcessAfterInitialization is the weaving point.

Full chain:

image.png

Key source (simplified):

// AnnotationAwareAspectJAutoProxyCreator
@Override
public Object postProcessAfterInitialization(@Nullable Object bean, String beanName) {
    if (bean != null) {
        // Determine if proxy needed (matches @Aspect)
        if (shouldProxy(bean.getClass())) {
            return createAopProxy().getProxy(getAopProxyConfigurer().getClassLoader());
        }
    }
    return bean;
}

// JdkDynamicAopProxy#invoke: when proxy object’s method is called
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
    // 1. Get matching interceptor chain
    List<Object> chain = this.advised
        .getInterceptorsAndDynamicInterceptionAdvice(method, targetClass);

    // 2. Execute interceptor chain (around -> before -> target -> after -> after-throwing)
    if (chain.isEmpty()) {
        return method.invoke(targetObject, args);
    }
    MethodInvocation invocation =
        new ReflectiveMethodInvocation(proxy, target, method, args, chain);
    return invocation.proceed(); // chain execution
}

Read this chain, and the following interview questions all connect:

The main AOP classes to read in order: AbstractAutoProxyCreator → AnnotationAwareAspectJAutoProxyCreator → AopProxy → JdkDynamicAopProxy / CglibAopProxy → ReflectiveMethodInvocation.

Correction: 7.0 continues to push unification of CGLIB proxies; don’t answer “default JDK proxy” from the 5.x era.

9. Correct posture for reading source

Methodology; this section saves at least three days of wrong turns.

9.1 Three mistakes to avoid

  1. Read from first line to last: You’re not reading a book; you’re reading code. Read with a question—e.g., “How exactly does @Autowired inject?” then trace the call stack. Don’t aim for full comprehension; grasp the main trunk first, fill details later;
  2. Only read, don’t write: The best way is to set breakpoints at key locations and step-debug, using IDEA’s Evaluate Expression to inspect variable changes. Iron rule: for every concept learned, write a demo under 30 lines;
  3. Read and forget: Use “small cuts” like @MapperScan principle, @Transactional principle; after each point, write a note and draw a sequence diagram. Notes in “exception stack → extension point → one-sentence principle” format, ready for interview recitation.

9.2 Three-stage mindset

image.png

Expanded into four steps:

  1. Set up environment: JDK 21/25 + Gradle 9.x, pull the spring-framework 7.0.8 tag (use the tag, not main), import into IDEA, first run official tests to confirm the source is alive;
  2. Grasp main trunk: entry locked at refresh()’s 12 steps, only follow doGetBean() / doCreateBean(); utility classes like StringUtils, ClassUtils are dictionary references, don’t read through;
  3. Master core: three-level cache and circular dependency, ConfigurationClassPostProcessor annotation parsing, AbstractAutoProxyCreator proxy weaving, @Transactional full chain—master these four, interviews are basically a walk. Bean lifecycle too long? Abstract into five words: Definition → Instantiation → Injection → Initialization → Proxy;
  4. Reverse output: write your own Starter, implement a BeanPostProcessor, then explain to others. If you can’t explain, you don’t understand.

A counterintuitive suggestion: early on, don’t rush to Debug line-by-line; first use “call stack + breakpoint hit count” to see the macro flow, or you’ll drown in dozens of stack frames.

Two more stuck points, solved in advance:

9.3 Four breakpoints to string IoC + lifecycle + AOP

Run a minimal Demo locally:

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

// breakpoint here
new AnnotationConfigApplicationContext(AppConfig.class);

Set breakpoints at these four locations:

AbstractApplicationContext#refresh
DefaultListableBeanFactory#preInstantiateSingletons
AbstractAutowireCapableBeanFactory#doCreateBean
AbstractAutoProxyCreator#postProcessAfterInitialization

10x more effective than reading source blindly.

9.4 Five-stage reading roadmap

Follow this order, don’t jump around:

Stage Topic Key classes Goal
1 Container startup main line AnnotationConfigApplicationContext, AbstractApplicationContext#refresh, obtainFreshBeanFactory, invokeBeanFactoryPostProcessors, registerBeanPostProcessors, finishBeanFactoryInitialization Know how a config becomes a pile of beans
2 Bean lifecycle main line DefaultListableBeanFactory#preInstantiateSingletons, doGetBean, DefaultSingletonBeanRegistry#getSingleton, doCreateBean, populateBean, initializeBean Know what a bean goes through from creation to usable
3 AOP main line AbstractAutoProxyCreator, AnnotationAwareAspectJAutoProxyCreator, AopProxy, JdkDynamicAopProxy, CglibAopProxy, ReflectiveMethodInvocation Know where proxies are generated, why AOP fails
4 Boot 4.x auto-config main line AutoConfigurationImportSelector, ImportCandidates, Condition, ConfigurationClassParser, ConfigurationClassPostProcessor Know why adding a starter auto-registers beans
5 Spring 7 new directions + on-demand AOT, GraalVM Native Image, RuntimeHints, Observability, Virtual Threads, Modularization; transactions, MVC, events on-demand Know the framework’s next steps. For native images, register RuntimeHints for reflection failures

Or take three routes: main thread (refresh()’s 12 steps), extension point special topics (BeanPostProcessor → BeanFactoryPostProcessor → ApplicationListener → InitializingBean/DisposableBean), interview high-frequency (circular dependency → AOP proxy → transaction failure, covering 80% of senior interview scenarios). When three routes converge, you’re through:

image.png

9.5 Before coding, set up the environment

Item Suggested config Description
JDK 21 / 25 7.0 min 17, but 21 is LTS, for virtual threads and so on
Source spring-framework 7.0.8 tag Use the tag, don’t pull main
Build Gradle 9.x Spring moved from Maven to Gradle
IDE IntelliJ IDEA Turn off extra inspections in Compiler to speed indexing
Run source Two paths ① Pull Maven dependencies and write a Demo to reverse-engineer (recommended); ② only import spring-beans/spring-context modules to IDE, skip web. Full Gradle build takes 20+ mins, don’t wait

How to verify understanding? Write an integration test using Spring 7’s testing capabilities, or check against 7.0.8 changelog to see if the class you care about changed.

10. Pitfall guide: bitter lessons

Compile the pitfalls mentioned (and not) into a table, bookmark it:

# Pitfall Symptom Root cause and solution
1 @Autowired in BFPP Startup BeanCurrentlyInCreationException BFPP runs too early, normal beans not ready. Use beanFactory.getBean() manually, or @Lazy
2 BPP returns null Subsequent processors break, bean disappears Container thinks you “ate” the bean. Must return original or proxy, never null
3 Inject other beans in BPP That bean initializes early, missing BPP Write BPP dependencies as static @Bean methods
4 Custom BPP doesn’t work Extension logic doesn’t run Implement Ordered or add @Order; note BPP registered at registerBeanPostProcessors stage, don’t getBean inside it
5 Registrar-registered bean injection fails NoSuchBeanDefinitionException Forgot autowireCandidate or scan path. Use RootBeanDefinition, ensure package path is in @ComponentScan range
6 FactoryBean & prefix getBean("xxx") gets product not factory FactoryBean has dual identity; use getBean("&xxx") for factory
7 Spring 7 legacy code throws NPE NPE after upgrade 7.0 JSpecify: unannotated types default non-null. Mark @Nullable or use Optional
8 @Transactional/@Async/@Retryable don’t work Annotation has no effect All proxy-based. Self-invocation doesn’t go through proxy; method can’t be private/final; exception not swallowed
9 Proxy over proxy Long call chain, unpredictable behavior Check AopUtils.isAopProxy(bean) first, return if already proxied
10 Can’t find custom annotation bean.getClass() returns Xxx$$SpringCGLIB$$0 Use AopProxyUtils.ultimateTargetClass(bean) and AnnotationUtils.findAnnotation
11 Constructor circular dependency Three-level cache can’t save Fails at instantiation, never reaches cache. Use @Lazy or setter injection; prototype circular also unsolvable
12 Circular dependency after upgrade Boot 2.6+ defaults to disallow spring.main.allow-circular-references default false. Refactor rather than turn on
13 Outdated version material Old tutorial code fails Use 7.0.8 source + official Release Notes; check gradle dependencies for true version
14 Environment baseline wrong JDK 11 fails with class version error Spring 7.x supports JDK 17-25+, official recommends 25; Jakarta EE 11 (Servlet 6.1)
15 Think all beans are raw objects Type conversion fails, annotation not found You may get CGLIB proxy, JDK proxy, or FactoryBean product
16 Only memorize three-level cache, not early exposure Still confused by variants Core isn’t three maps, but four timings: when created, when early-exposed, when populated, when truly initialized
17 Auto-configuration not working @Conditional not satisfied Open condition evaluation log (ConditionEvaluator); in Boot 4, start from AutoConfigurationImportSelector

Spring 7.0 upgrade checklist, go through each item:

11. Interview cheat sheet (memorize directly)

High-frequency question quick reference

Interview question Memorized answer Source-level answer
How does Spring manage beans? “IoC container manages bean lifecycle” “DefaultListableBeanFactory maintains beanDefinitionMap (String→BeanDefinition); doGetBean gets/creates beans via getSingleton using three-level cache”
How does @Autowired work? “Spring auto-injects dependencies” “AutowiredAnnotationBeanPostProcessor in postProcessProperties finds fields/methods annotated @Autowired via reflection and injects”
How are transactions implemented? “AOP + annotation” “TransactionInterceptor implements MethodInterceptor, uses TransactionManager to begin/commit/rollback; proxy intercepts method calls”
How does the event mechanism work? “Publish-subscribe pattern” “ApplicationEventPublisher publishes event → SimpleApplicationEventMulticaster broadcasts → matched @EventListener listener methods execute”
How does Spring Boot auto-config work? “@SpringBootApplication” “@EnableAutoConfiguration → AutoConfigurationImportSelector → reads META-INF/spring/autoconfigure.imports → @ConditionalOnXXX determines loading”

60-second oral template

Interviewer asks “why read Spring source code,” you can say:

My goal in reading Spring source is simple: give myself the ability to extend the framework.

Specifically, I break 7.0.8’s container startup into three steps: blueprint (invokeBeanFactoryPostProcessors collects BeanDefinition), tools (registerBeanPostProcessors), construction (finishBeanFactoryInitialization). Production issues first locate to which step, and you’re mostly diagnosed.

For extension capability, I use three types of hooks: modify blueprints with BeanDefinitionRegistryPostProcessor or Spring 7’s new BeanRegistrar; modify beans with BeanPostProcessor—Spring’s own @Autowired, @Transactional, @Retryable all work this way; for early exposure use SmartInstantiationAwareBeanPostProcessor—the key to three-level cache and circular dependency is in its getEarlyBeanReference.

As for the “three-level cache,” my understanding is: level three stores a factory, not an object, to defer the decision—only when a circular reference truly occurs does the factory execute, at which point it decides whether to expose the raw object or an AOP proxy.

After this, the interviewer won’t ask “are you memorizing?”

Follow-up: “What have you extended?”

❌ Wrong answer: “I used @Component…” (that’s using, not extending)

✅ Right pattern: Scenario → extension point → effect → incidentally read source. Example:

In our project, interfaces needed unified time monitoring. I didn’t touch business code; I wrote a BeanPostProcessor that intercepts beans annotated @RestController, wrapping each with a dynamic proxy in postProcessAfterInitialization. Debugging slow endpoints after release was super convenient. I later found that Spring’s built-in AbstractAutoProxyCreator follows the same idea, so I read its source, and learned how it handles early proxies in circular dependencies.

12. Conclusion

Three sentences to take away:

  1. Spring’s core isn’t the Bean, but the system of creation, management, and extension of Beans;
  2. The goal of reading source isn’t to memorize class names, but to find extension points;
  3. The true mark of mastering Spring is being able to build your own framework capabilities on top of it.

Memorization is someone else’s chewed conclusions; source is the path you walk yourself. Memorization determines whether you pass the initial screen; source determines whether you get the evaluation “can independently solve framework-level problems.” From today, treat Spring as a “framework you can extend,” not “knowledge to memorize.”

Next article starts the main line: “Spring Source Code Interpretation (1): Line-by-line breakdown of refresh()’s 12 steps”, taking apart AbstractApplicationContext, focusing on steps 5, 6, 11, and answering how BeanDefinition “grows” from @Configuration. Series roadmap; every article answers three fixed questions: what problem does this source solve, what extension point does it leave, and how do I verify my understanding?

image.png

If this saved you three hours of searching, click “like” and “in.” I publish a Spring source deep-dive weekly, no memorization, only substance. Follow me.

Finally, a concrete question: When reading Spring source, which step stuck with you the longest? Three-level cache, AOP proxy, or refresh()’s 12 steps? Comment below; I’ll reply to the top-voted ones individually.


This article is verified against Spring Framework 7.0.8; code runs on JDK 17 + official jars. Source snippets are simplified for understanding; refer to official source for exact implementations.

Comments

Top 3 of 6 from juejin.cn, machine-translated. The original thread is authoritative.

用户580095225348 1 likes

Master, awesome, old soldiers never die [striving]

Rain的Java大神之路

Thank you, big shot, for your support, keep it up

约洛 1 likes

Interviewer: Recite the source code

Rain的Java大神之路

Master, 6, haha, that can't be memorized

西瓜大大 1 likes

Although you are a master. But isn't everything AI now? In the future, AI will communicate in 0101... Code frameworks and languages are still just for humans to see...

Rain的Java大神之路

Master, 6, haha, what you said is indeed the trend, but it's still useful