Spring 7.0.8 Source Code Reading Guide: Setup, Modules & 6 Core Deep Dives
A comprehensive guide to reading Spring Framework 7.0.8 source code, covering environment setup with JDK 25/Gradle, module architecture overview, six core modules (core, beans, context, AOP, tx, webmvc) deep dive with key classes and debugging breakpoints, reading methodology, interview Q&A, and Spring 7.0 new features.
Reading font

Why Read Spring Source Code and How to Answer in Interviews
In real development we often face scenarios: a bean refuses to inject, @Transactional doesn't work, AOP aspect order is wrong, or circular dependencies cause startup failures with unreadable stack traces. Source code is your map. Reading source code serves four purposes: know where to look when problems arise, learn design thinking from experts, enable secondary customization, and write more elegant code. The salary gap between those who understand internals and those who only call APIs is obvious.
When asked "How do you read Spring source code?" in an interview, answer with three sentences:
Interviewer : You wrote "deeply read Spring source code" on your resume. Tell me how you read it. Me : I read by main flow, not by package . Three sentences summary: ① Container is the skeleton : all capabilities hang on the 12 steps of refresh() ; memorize the skeleton first. ② Bean lifecycle is the flesh : getBean → createBean → populateBean → initializeBean ; AOP, transactions, injection are hooks on this chain. ③ Web is the skin : DispatcherServlet#doDispatch those dozens of lines are the heart of MVC. I locally compile v7.0.8 source, set breakpoint directly on AbstractApplicationContext#refresh() , run a minimal demo and trace the call stack.
Interviewer : Why 7.0? Me : Because production is migrating to Spring Boot 4. 7.0 is the Jakarta EE 11 baseline, Jackson 3, JSpecify null-safety generation. Reading old version source code may pass interviews but won't match production.
If you only have 30 seconds, use this compressed version: "I read Spring Framework 7.0.8, cloned and built with IDEA + Gradle Wrapper. I don't grab all modules; I deeply read six: spring-core, spring-beans, spring-context, spring-aop, spring-tx, spring-webmvc. My method is scenario-driven + breakpoint tracing call chains — from refresh() trace down through bean loading, instantiation, initialization, AOP proxying."
This answer proves you read the new version, have selection criteria, and have a methodology. Interviewers want to hear your methodology, not memorized class names.
Version Baseline and Environment Checklist: Don't Crash at the Starting Line
Align baselines first to avoid version mismatches:
JDK (runtime) : Minimum 17 , officially compatible up to 25/27. Spring 7.0+ no longer supports JDK 8/11.
JDK (compile source) : Officially requires 25 . Repo .sdkmanrc pins java=25; Gradle toolchain also uses 25.
Build tool : Use repo's Gradle Wrapper . Don't install Gradle yourself; version per gradle-wrapper.properties.
IDE : IntelliJ IDEA 2023.x+, recommend 2024.x. Community edition sufficient; better Gradle and new Java support.
Jakarta EE : 11 baseline (Tomcat 11, Hibernate ORM 7, Hibernate Validator 9). javax.* fully migrated to jakarta.*.
Memory/Disk : Recommend 16G+ (32G better), ample disk. Source compilation + dependency cache are resource-heavy.
90% pitfall : "Runtime baseline JDK 17" ≠ "Compile source with JDK 17". Running your demo with 17 is fine, but compiling Spring source officially requires JDK 25. In IDEA, Gradle JVM points to 25, Project SDK 17+ is fine. Compilation errors like invalid source release or toolchain not found are usually due to this mismatch.
Mnemonic: 17 runs, 25 better; Jakarta 11, no javax.
Major Changes in Spring 7.0
Jakarta EE 11 baseline : javax.servlet.* → jakarta.servlet.*, javax.annotation.* → jakarta.annotation.*, etc. 7.0 completely removes support for javax.annotation and javax.inject annotations ; old projects must migrate before upgrading.
JSpecify null-safety : Entire codebase uses JSpecify annotations replacing old JSR-305 style; core layer fully null-marked, friendlier to Kotlin.
Jackson 3 promoted : Package moved from com.fasterxml.jackson to tools.jackson; Jackson 2 deprecated.
RestTemplate enters deprecation countdown : 7.1 will add @Deprecated; official recommends declarative HTTP client @HttpExchange.
Built-in resilience support : @Retryable, @CircuitBreaker, @ConcurrencyLimit natively supported; no need for Spring Retry / Resilience4j.
spring-jcl removed : Replaced by Apache Commons Logging 1.3.0 (transitive via spring-core).
Undertow removed : Because it doesn't support Servlet 6.1.
AOP defaults to unified CGLIB proxy ( proxyTargetClass=true), consistent with Spring Boot.
Hands-On Environment Setup: Get Source Running in 30 Minutes
Step 1: Clone Source, Checkout Stable Tag
# GitHub official source
git clone https://github.com/spring-projects/spring-framework.git
cd spring-framework
# Domestic Gitee mirror also works
# git clone https://gitee.com/mirrors/Spring-Framework.git
# Checkout 7.0.8 release tag (2026-06-08)
git checkout v7.0.8Don't read main branch ; main is always ahead of stable release, behavior won't match. Fix a version and read through; this series locks v7.0.8.
Strongly recommend forking to your own account first: freely add Chinese comments, tag learning progress, maybe even submit PRs to Spring later.
Step 2: Configure Domestic Mirror to Fix Gradle Slowness
Create ~/.gradle/init.gradle (Windows: C:\Users\YourUsername\.gradle\init.gradle):
allprojects {
buildscript {
repositories {
maven { url 'https://maven.aliyun.com/repository/public' }
maven { url 'https://maven.aliyun.com/repository/spring' }
mavenCentral()
gradlePluginPortal()
}
}
repositories {
maven { url 'https://maven.aliyun.com/repository/public' }
maven { url 'https://maven.aliyun.com/repository/spring' }
mavenCentral()
}
}Some tutorials tell you to modify repo root build.gradle ; I don't recommend — use user-level init.gradle , doesn't pollute source repo, keeps git operations clean.
Tune gradle.properties (adjust per machine):
org.gradle.caching=true
org.gradle.parallel=true
org.gradle.jvmargs=-Xmx4g -XX:MaxMetaspaceSize=1gStep 3: Pre-compile Core Modules (Compile Before Import to Avoid IDEA Errors)
Never run ./gradlew build full build first — too slow, some modules may fail locally. Only compile modules you'll read: ./gradlew -PskipDocs :spring-core:compileJava — Compile only, no tests, no docs. Daily iteration, fastest. ./gradlew :spring-oxm:compileTestJava — Pre-compile spring-oxm. It has repackaged dependencies and is depended on by others; must compile first or will error . ./gradlew :spring-beans:compileTestJava — Compile and compile test code. Verify environment; seeing BUILD SUCCESSFUL means OK. ./gradlew build -x test -x javadoc — Full compile but skip tests and docs. When you want one-shot. ./gradlew :spring-context:test --tests "*Refresh*" — Run single test class. Verify specific behavior. ./gradlew publishToMavenLocal — Install to local ~/.m2. Your own demo wants to depend on locally compiled version.
On Windows replace ./gradlew with gradlew.bat.
Three iron rules: ❌ Don't install Gradle yourself; use repo's gradlew (wrapper locks version) ❌ Don't run ./gradlew clean casually; incremental compilation is Gradle's lifeline ✅ First compile add -x test , saves half the time
Step 4: IDEA Import
File → Open(or New → Project from Existing Sources) select project root, choose Gradle Wrapper mode. Settings → Build Tools → Gradle: Gradle JVM points to JDK 25 , Project SDK 17+ is fine.
Check repo root import-into-idea.md — official step-by-step guide.
Exclude spring-aspects module (needs AspectJ compile-time weaving; without AJDT it stalls compilation), no impact on reading 6 core modules.
Keep repo's .idea/ directory with code style config; don't delete.
Optional: check Delegate IDE build/run actions to Gradle for consistent build behavior.
First sync downloads dependencies, 5-30 minutes. If indexing too slow, keep only spring-core/beans/context/aop modules, exclude others.
Step 5: Create a Debug Demo Module (Most Critical Step)
Source code is for debugging, not just "reading". Create an independent spring-debug module, depend on spring-context, write 20 lines:
public class DebugMain {
public static void main(String[] args) {
// Breakpoint here, Step Into all the way
AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext(AppConfig.class);
UserService userService = ctx.getBean(UserService.class);
userService.hello();
ctx.close();
}
@Configuration
@ComponentScan("com.example.demo")
@EnableTransactionManagement
@EnableAspectJAutoProxy
static class AppConfig {}
}
@Service
class UserService {
public void hello() {
System.out.println("Hello Spring 7.0.8!");
}
}Run and see Hello Spring 7.0.8! — environment ready.
Three golden breakpoints, hit them and you win 80%:
① AbstractApplicationContext#refresh() ← Container outline (12 steps)
② AbstractBeanFactory#doGetBean() ← How each bean comes to be
③ AbstractAutowireCapableBeanFactory#createBean ← Instantiate → Populate → InitializeAdd a conditional breakpoint technique: right-click breakpoint → Condition → enter beanName.equals("userService"); only pauses when target bean passes, cuts 90% noise.
Lazy Alternative: Read Without Compiling Source
If you just want to start fast, lightweight route: Create a Spring Boot 4.x (or pure Maven) project, directly depend on 7.0.8 release artifacts . IDEA auto-downloads and attaches sources, same breakpoint debugging:
<properties>
<java.version>21</java.version>
<spring-framework.version>7.0.8</spring-framework.version>
</properties>
<dependencyManagement>
<dependencies>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-framework-bom</artifactId>
<version>${spring-framework.version}</version>
<type>pom</type>
<scope>import</scope>
</dependency>
</dependencies>
</dependencyManagement>
<dependencies>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
</dependency>
<!-- spring-aop / spring-tx / spring-webmvc add as needed -->
</dependencies>Adding spring-context transitively pulls spring-core, spring-beans, spring-aop, covering most learning needs. To make your demo depend on locally compiled version, use publishToMavenLocal mentioned earlier.
Environment Pitfall Cheat Sheet
Symptom : Could not find org.gradle.wrapper.GradleWrapperMain — Cause : Wrapper jar missing — Solution : Check gradle/wrapper/gradle-wrapper.jar, copy from another project.
Symptom : Dependency download stuck / Could not resolve... — Cause : Network issue — Solution : Use domestic mirror; if needed --refresh-dependencies.
Symptom : Gradle sync stuck at buildSrc — Cause : 7.x uses buildSrc for build logic — Solution : Configure proxy or Aliyun mirror.
Symptom : spring-aop compile error org.aspectj not found — Cause : AspectJ weaver missing — Solution : Run ./gradlew :spring-aop:compileJava separately, or manually add aspectjweaver.
Symptom : spring-oxm compile error — Cause : JAXB code generation failed — Solution : Run :spring-oxm:compileTestJava first.
Symptom : spring-aspects error — Cause : Needs AspectJ compile-time weaving — Solution : Directly Exclude; doesn't affect core reading.
Symptom : OutOfMemoryError — Cause : Insufficient memory — Solution : Increase -Xmx in gradle.properties.
Symptom : Unsupported class file / invalid source release — Cause : JDK version mismatch — Solution : Compile with 25, run with 17+, configure Gradle JVM separately.
Symptom : GBK encoding error — Cause : File encoding inconsistency — Solution : Set IDE global to UTF-8.
Symptom : Lombok not working, methods all red — Cause : Missing plugin — Solution : Install Lombok plugin + enable Enable annotation processing.
Symptom : Many Kotlin/optional yellow warnings — Cause : Optional dependencies — Solution : Ignore; doesn't affect reading.
Symptom : Breakpoint won't step into framework code — Cause : Depending on jar not source module — Solution : Create demo module in source project, or publishToMavenLocal.
Symptom : Tests all red — Cause : Missing Docker/database env — Solution : First compile with -x test.
Environment cleared, next look at the map — Spring is huge, diving in without a map leads to quitting in two days.
Module Panorama: See the Map Before Choosing Battlefields
Spring is not a monolith but modular Lego: 20+ modules, officially grouped into six categories, import on demand, clear responsibilities, unidirectional dependencies . Full source 2M+ lines; reading all equals reading none.
4.1 Layered Architecture Diagram
Core Container consists of core, beans, context, expression; core and beans provide the most fundamental parts: IoC and dependency injection.
4.2 Module Responsibility Cheat Sheet (Memorize This Table for Interviews)
Core — spring-core: Tool foundation: Resource abstraction, type conversion, reflection enhancement, Assert, JSpecify null-safety, bytecode parsing. Priority: ⭐⭐⭐
Core — spring-beans: Bean's "household register": BeanDefinition, BeanFactory, dependency injection, three-level cache. Priority: ⭐⭐⭐⭐⭐
Core — spring-context: Container "brain": ApplicationContext, refresh(), events, i18n, Environment. Priority: ⭐⭐⭐⭐⭐
Core — spring-expression: SpEL expressions, used by @Value, cache annotations, Security. Priority: ⭐⭐
AOP — spring-aop: Dynamic proxy, Advisor/Advice/Pointcut, foundation for transactions and @Async. Priority: ⭐⭐⭐⭐⭐
AOP — spring-aspects: AspectJ integration, @Aspect annotation support. Priority: ⭐⭐
AOP — spring-instrument: Class loading enhancement (class instrumentation), for server environments. Priority: ⭐
Data — spring-jdbc: JdbcTemplate, data source abstraction, unified exception hierarchy. Priority: ⭐⭐⭐
Data — spring-orm: JPA/Hibernate ORM integration (Spring doesn't implement ORM, only integration and transactions). Priority: ⭐⭐
Data — spring-tx: Transaction abstraction, PlatformTransactionManager, declarative transaction full chain. Priority: ⭐⭐⭐⭐⭐
Data — spring-oxm: Object/XML mapping, still released in 7.0 but rarely used daily. Priority: ⭐
Data — spring-r2dbc: Reactive database access. Priority: ⭐
Web — spring-web: HTTP basic tools, Servlet integration, HttpMessageConverter. Priority: ⭐⭐⭐
Web — spring-webmvc: Servlet stack MVC: DispatcherServlet + nine components. Priority: ⭐⭐⭐⭐⭐
Web — spring-webflux: Reactive Web (Reactor + Netty), different paradigm, skip initially. Priority: ⭐⭐
Web — spring-websocket: WebSocket / STOMP protocol support. Priority: ⭐⭐
Messaging — spring-messaging: Messaging programming model, STOMP/AMQP/JMS abstraction. Priority: ⭐⭐
Test — spring-test: TestContext framework, MockMvc, @SpringBootTest underlying. Priority: ⭐⭐
4.3 Dependency Relationship: Arrows Always Point to Core
(A → B means B builds on A.)
Core conclusion : spring-context is the hub of the entire framework; read it and AOP, transactions, MVC are its extensions. Read source code following dependencies from bottom up — many start by gnawing ApplicationContext implementations, find methods long and winding, because they skipped BeanFactory foundation.
4.4 Why These 6 Modules?
This series deep-reads: spring-core → spring-beans → spring-context → spring-aop → spring-tx → spring-webmvc.
Reason: these 6 cover 90% of main flows of Spring's three core capabilities, 90% of interview topics, and 80% of daily development scenarios:
IoC container lifecycle → core + beans + context AOP dynamic proxy → aop ( @Transactional, @Async underlying all here)
Transaction control → tx (all "transaction failure scenarios" asked in interviews are here)
Web request handling → webmvc (complete journey of an HTTP request inside Spring)
Remaining webflux, messaging can be supplemented later. Biggest beginner trap is "want to read everything".
Each module gets an "entry class map" for targeted reading:
spring-core : Entry ClassPathResource; Must-read: DefaultResourceLoader, ConversionService, Assert; Key question: How are resources uniformly abstracted? Essence: Foundation for all IO/conversion.
spring-beans : Entry DefaultListableBeanFactory; Must-read: AbstractBeanFactory#doGetBean, doCreateBean, DefaultSingletonBeanRegistry; Key question: How many steps from "blueprint" to "product"? How is circular dependency solved? Essence: BeanDefinition → Instance → Populate → Initialize.
spring-context : Entry AnnotationConfigApplicationContext; Must-read: AbstractApplicationContext#refresh, ConfigurationClassPostProcessor; Key question: When does @Configuration become BeanDefinition? Essence: BeanFactory's "enhanced shell".
spring-aop : Entry AnnotationAwareAspectJAutoProxyCreator; Must-read: AbstractAutoProxyCreator#wrapIfNecessary, DefaultAopProxyFactory, JdkDynamicAopProxy; Key question: When is proxy generated? JDK or CGLIB? Essence: BPP replaces object after initialization.
spring-tx : Entry @EnableTransactionManagement; Must-read: TransactionInterceptor#invoke, DataSourceTransactionManager, TransactionSynchronizationManager; Key question: Why does transaction rely on AOP? How is connection bound to thread? Essence: Interceptor + ThreadLocal.
spring-webmvc : Entry DispatcherServlet#doDispatch; Must-read: RequestMappingHandlerMapping, RequestResponseBodyMethodProcessor, HandlerExceptionResolver; Key question: How does request find Controller method? Essence: Nine components + one loop.
Map ready, don't rush to flip code — wrong method, three days and you'll quit. This section's methodology is my 5-year distilled essence.
Reading Methodology: Don't Be a Dictionary, Be a Detective
Many fail reading source code not because it's hard, but wrong posture: reading line by line from main, three days still looking at log prints, then quit. Remember this combo.
5.1 Three-Pass Reading Method
Corresponding to three perspectives:
First pass: main flow : Goal not to understand every class, but clarify "how container starts, how beans are created, how dependencies are injected".
Second pass: core objects : BeanDefinition, BeanFactory, DefaultListableBeanFactory, ApplicationContext, BeanPostProcessor, BeanFactoryPostProcessor — state changes of these protagonists.
Third pass: extension points : BeanFactoryPostProcessor, BeanPostProcessor, InstantiationAwareBeanPostProcessor, SmartInitializingSingleton, ApplicationListener — Spring's real power is not hardcoded flows but extension points.
5.2 Four Iron Rules
Read with questions, not aimlessly . Wrong: "I'll read all Spring source" (impossible); Right: "I'll figure out @Transactional implementation" (doable).
Single-thread mainline principle : Only read main thread; async, events, compatibility branches skip first, otherwise get lost eight times a day. Spring source 30% core logic, 70% compatibility/extensions; first pass just connect the 30% main trunk.
Guess by name + immediate verification : Spring class names are extremely honest, AnnotationAwareAspectJAutoProxyCreator = annotation-driven AspectJ auto proxy creator, not a word to change.
Callbacks and lambdas are biggest obstacles : getSingleton(beanName, () -> createBean(...)) — set breakpoint inside lambda body, check Call Stack to see who called ObjectFactory.getObject().
One lifesaving trick: Output matters more than imagination . System.out.println(bean.getClass()) saves you — you'll see OrderService$$SpringCGLIB$$0, proxy no longer mystic.
5.3 Debug Three-Piece Set
Step Into into interface : IDEA jumps directly to implementation, cures "click interface don't know which implementation".
Evaluate Expression : At breakpoint execute beanFactory.getBeanDefinitionNames(), real-time view of registered beans.
Method Breakpoint : Set on refresh(), any subclass call stops, cures "jumping around lost". If overshoot, use Drop Frame to backtrack.
Auxiliary: open Frames panel to see full call chain; set log to logging.level.org.springframework=DEBUG; write custom BeanPostProcessor to probe:
@Component
public class MyBeanPostProcessor implements BeanPostProcessor {
@Override
public Object postProcessBeforeInitialization(Object bean, String beanName) {
System.out.println(">>> Pre-process: " + beanName + " -> " + bean.getClass().getSimpleName());
return bean;
}
}5.4 Breakpoint Location Cheat Sheet (Just Set These)
spring-context : AbstractApplicationContext#refresh() — Container startup 12-step outline, core of cores.
spring-context : finishBeanFactoryInitialization() — Singleton bean batch instantiation entry.
spring-beans : DefaultListableBeanFactory#preInstantiateSingletons() — Non-lazy singleton pre-instantiation loop.
spring-beans : AbstractBeanFactory#doGetBean() — Starting point of each bean "from nothing to existence".
spring-beans : AbstractAutowireCapableBeanFactory#doCreateBean() — Instantiate → Inject → Initialize main chain, circular dependency.
spring-beans : populateBean() / initializeBean() — @Autowired injection, Aware callbacks, initialization order.
spring-beans : DefaultSingletonBeanRegistry#getSingleton() / addSingletonFactory() — Three-level cache lookup and promotion.
spring-aop : AbstractAutoProxyCreator#postProcessAfterInitialization() — AOP proxy creation timing.
spring-tx : TransactionInterceptor#invoke() — Transaction begin, commit, rollback.
spring-webmvc : DispatcherServlet#doDispatch() — HTTP request processing complete flow.
Interview killer : Master just refresh() this one method, and you can answer 80% of IoC-related interview questions.
5.5 Structured Notes: One Diagram, Two Breakpoints, Three Notes
In IDEA, add structured comments to key classes, draw flow sketches after reading — deeper impression than just reading code:
// ========== Entry Layer ==========
// AnnotationConfigApplicationContext → calls refresh() in constructor
// ========== Container Core ==========
// AbstractApplicationContext#refresh() → 12-step template method
// ========== Bean Factory ==========
// DefaultListableBeanFactory → BeanDefinition registry
// └── registerBeanDefinition() → stores in beanDefinitionMap
// ========== Bean Creation ==========
// AbstractAutowireCapableBeanFactory#doCreateBean()
// ├── createBeanInstance() → Instantiation
// ├── populateBean() → Property injection (@Autowired)
// └── initializeBean() → Initialization (Aware / BPP / init-method)Mnemonic: One diagram, two breakpoints, three notes — draw flowcharts, set conditional breakpoints, write structured comments.
Methodology done, now the heaviest part: core code speed-read of 6 deep-read modules. Each snippet simplified and pseudo-coded (exception branches and logs removed), get familiar first; later articles will dive line by line.
Six Core Modules Core Code Speed-Read
6.1 spring-core: Spring's "Toolman" Foundation
Positioning : Bottom toolkit for all modules, no business logic, all basic capabilities — resource abstraction, type conversion, generic parsing, utilities, null-safety annotations. Core package structure:
org.springframework.core/
├── annotation/ # Annotation support
├── io/ # Resource loading (Resource, ResourceLoader)
├── convert/ # Type conversion (ConversionService)
├── util/ # Utilities (ClassUtils, StringUtils)
├── exception/ # Exception hierarchy (NestedExceptionUtils)
└── type/ # Type abstraction (ResolvableType)Core entry: Resource interface . Why can Spring load resources from classpath, filesystem, URL, even byte arrays? Because of this unified abstraction:
// spring-core: org.springframework.core.io.Resource
public interface Resource extends InputStreamSource {
boolean exists();
boolean isReadable();
URL getURL() throws IOException;
File getFile() throws IOException;
Resource createRelative(String relativePath) throws IOException;
String getFilename();
long getLastModified();
String getDescription();
}Common implementations: ClassPathResource, FileSystemResource, UrlResource, ServletContextResource, InputStreamResource. Spring's config loading, annotation scanning all based on this abstraction.
Technical highlight : Uses Adapter + Strategy pattern to unify access to all resource types; upper code doesn't care where resource comes from, lower implementation swap doesn't affect upper. Spring 7.x fully introduces JSpecify null-safety annotations; entire core layer null-marked.
Often overlooked gem: ResolvableType. Java generics have type erasure, but when Spring injects List<User> it matches precisely, thanks to it:
// Spring uses ResolvableType to retain and parse generic info
ResolvableType type = ResolvableType.forClass(UserServiceImpl.class);
// Trace via generic superclass/interface to resolve actual generic parameters6.2 spring-beans: IoC Underlying Core
Positioning : Core factory for bean definition, registration, creation; underlying implementation of dependency injection. Package structure:
org.springframework.beans/
├── factory/
│ ├── BeanFactory.java # Bottom-most interface
│ ├── ListableBeanFactory.java # List-style access
│ ├── HierarchicalBeanFactory.java # Hierarchical factory
│ ├── AutowireCapableBeanFactory.java # Autowiring
│ └── ConfigurableBeanFactory.java # Configurable factory
├── support/
│ ├── AbstractBeanFactory.java # Abstract default implementation
│ └── DefaultListableBeanFactory.java # Final implementation (99% scenarios)
├── BeanDefinition.java # Bean definition metadata
└── wrapper/BeanWrapper.java # Bean property access wrapperCore entry: BeanFactory interface , IoC container's top parent, extremely plain:
public interface BeanFactory {
String FACTORY_BEAN_PREFIX = "&";
Object getBean(String name) throws BeansException;
<T> T getBean(String name, Class<T> requiredType) throws BeansException;
boolean containsBean(String name);
boolean isSingleton(String name) throws NoSuchBeanDefinitionException;
boolean isPrototype(String name) throws NoSuchBeanDefinitionException;
Class<?> getType(String name) throws NoSuchBeanDefinitionException;
}Note that FACTORY_BEAN_PREFIX: getBean("&xxx") gets FactoryBean itself, getBean("xxx") gets object it produces.
Must clarify two easily confused pairs:
BeanFactory vs FactoryBean : BeanFactory is the restaurant , manages all beans; FactoryBean is the cooking machine in kitchen — it's a bean itself, but its getObject() produces the final object. Spring integrates MyBatis, each Mapper proxy object is produced by MapperFactoryBean . BeanFactory vs ApplicationContext : Former is bottom factory, uses lazy loading ( getBean triggers instantiation); latter is developer-facing advanced container, extends BeanFactory with event publishing, i18n, resource loading, annotation-driven, pre-instantiates singletons at startup. Real projects almost always use ApplicationContext .
Bean's "blueprint" is BeanDefinition — why doesn't Spring directly new objects? Because metadata (class name, scope, factory method, lazy flag) collected first, then unified parsing, unified enhancement:
public interface BeanDefinition extends AttributeAccessor, BeanMetadataElement {
String getBeanClassName(); // Bean class name
String getFactoryBeanName(); // Factory bean name
String getFactoryMethodName(); // Factory method name
String getScope(); // singleton / prototype
boolean isSingleton();
boolean isPrototype();
boolean isLazyInit();
// ... many more attribute definition methods
}Core method: doCreateBean — IoC's heart. How bean is newed, how dependencies injected, how circular dependency solved, all here:
// spring-beans: AbstractAutowireCapableBeanFactory (excerpt, comments by author)
protected Object doCreateBean(String beanName, RootBeanDefinition mbd, @Nullable Object[] args) {
BeanWrapper instanceWrapper = null;
if (mbd.isSingleton()) {
instanceWrapper = this.factoryBeanInstanceCache.remove(beanName);
}
// 1. Instantiate: reflective constructor call (properties not injected yet)
if (instanceWrapper == null) {
instanceWrapper = createBeanInstance(beanName, mbd, args);
}
Object bean = instanceWrapper.getWrappedInstance();
// 2. Three-level cache: early expose factory, key to solving circular dependency
boolean earlySingletonExposure = (mbd.isSingleton() && this.allowCircularReferences
&& isSingletonCurrentlyInCreation(beanName));
if (earlySingletonExposure) {
addSingletonFactory(beanName, () -> getEarlyBeanReference(beanName, mbd, bean));
}
// 3. populateBean: dependency injection happens here (@Autowired resolved here)
populateBean(beanName, mbd, instanceWrapper);
// 4. initializeBean: Aware callbacks → BPP before → init-method → BPP after
// AOP proxy object generated here by BeanPostProcessor
Object exposedObject = initializeBean(beanName, bean, mbd);
return exposedObject;
}One layer up, createBean has a short-circuit logic resolveBeforeInstantiation() — InstantiationAwareBeanPostProcessor can return proxy object before instantiation; AOP's "early proxy" goes here.
Non-lazy singletons are batch-created at container startup by preInstantiateSingletons():
// DefaultListableBeanFactory#preInstantiateSingletons (excerpt)
for (String beanName : beanNames) {
RootBeanDefinition bd = getMergedLocalBeanDefinition(beanName);
if (!bd.isAbstract() && bd.isSingleton() && !bd.isLazyInit()) {
if (isFactoryBean(beanName)) {
Object bean = getBean(FACTORY_BEAN_PREFIX + beanName);
// FactoryBean special handling
} else {
getBean(beanName); // Actually triggers ordinary bean creation
}
}
}Interview high-frequency: Three-level cache . Look at three Maps, that's the whole secret:
// DefaultSingletonBeanRegistry
/** Level 1 cache: fully initialized finished singletons */
private final Map<String, Object> singletonObjects = new ConcurrentHashMap<>(256);
/** Level 2 cache: early exposed semi-finished (instantiated, not fully initialized) */
private final Map<String, Object> earlySingletonObjects = new ConcurrentHashMap<>(16);
/** Level 3 cache: object factories, for generating early references (AOP proxy intervenes early) */
private final Map<String, ObjectFactory<?>> singletonFactories = new HashMap<>(16);
protected Object getSingleton(String beanName, boolean allowEarlyReference) {
Object o = this.singletonObjects.get(beanName); // 1. Finished product?
if (o == null && isSingletonCurrentlyInCreation(beanName)) {
synchronized (this.singletonObjects) {
o = this.earlySingletonObjects.get(beanName); // 2. Semi-finished?
if (o == null && allowEarlyReference) {
ObjectFactory<?> factory = this.singletonFactories.get(beanName); // 3. Factory?
if (factory != null) {
o = factory.getObject(); // Call getEarlyBeanReference, AOP may weave early
this.earlySingletonObjects.put(beanName, o); // Promote to level 2
this.singletonFactories.remove(beanName);
}
}
}
}
return o;
}Walk through with A, B mutually dependent:
Three truths, high interview differentiation:
Constructor injection circular dependency unsolvable — objects can't be instantiated, no "semi-finished" to expose. Spring Framework defaults allowCircularReferences = true</strong>, but <strong>Spring Boot from 2.6 defaults to false</strong> (Boot 4 will show that famous circular ASCII error diagram).</li><li><strong>Real reason for three-level cache isn't "early reference" but "early reference object may need AOP proxy"</strong> — if no proxy needed, level 2 suffices. Factory decides at <code>getObject() whether to return raw object or proxy, ensuring container everywhere gets same reference.
I used to fall in this pit: read ten articles still confused, finally set breakpoints in getSingleton() and addSingletonFactory(), watched two mutually dependent beans step by step cache changes, truly transparent. Don't just read; trace with breakpoints yourself.
6.3 spring-context: Developer-Facing IoC Container
Positioning : Built on beans, provides complete application context capabilities — event mechanism, i18n, environment abstraction, annotation-driven, the IoC container we use daily.
Core entry: AbstractApplicationContext#refresh() — container startup master switch, 100 lines most worth reading in whole framework. No subclass overrides it:
// spring-context: AbstractApplicationContext
@Override
public void refresh() throws BeansException, IllegalStateException {
synchronized (this.startupShutdownMonitor) {
prepareRefresh(); // ① Pre-refresh prep: startup time, status, env validation
ConfigurableListableBeanFactory beanFactory =
obtainFreshBeanFactory(); // ② Obtain fresh BeanFactory
prepareBeanFactory(beanFactory); // ③ Configure standard features: ClassLoader, SpEL, built-in BPP
try {
postProcessBeanFactory(beanFactory); // ④ Template method: subclass extension (Web container registers Servlet context here)
invokeBeanFactoryPostProcessors(beanFactory); // ⑤ ★ Execute all BFPP: parse @Configuration, @ComponentScan, register BeanDefinition
registerBeanPostProcessors(beanFactory); // ⑥ ★ Register BPP: @Autowired, AOP, transaction hooks in place
initMessageSource(); // ⑦ Initialize i18n
initApplicationEventMulticaster(); // ⑧ Initialize event broadcaster
onRefresh(); // ⑨ Template method: subclass custom refresh (Boot's web server starts here)
registerListeners(); // ⑩ Register event listeners
finishBeanFactoryInitialization(beanFactory); // ⑪ ★★★ Instantiate all non-lazy singletons (getBean actually happens here)
finishRefresh(); // ⑫ LifecycleProcessor + publish ContextRefreshedEvent
} catch (BeansException ex) {
destroyBeans();
cancelRefresh(ex);
throw ex;
} finally {
resetCommonCaches();
}
}
}Technical highlight : This is a textbook Template Method pattern — common flow fixed in parent, variation points via hooks like onRefresh() , postProcessBeanFactory() delegated to subclasses; subclasses can only change details, not skeleton. Understanding this explains why Spring organizes huge startup process so neatly.
Mnemonic:
refresh → obtain factory → prepare factory → post-process → execute post-processors → register post-processors → i18n → broadcaster → sub-refresh → listeners → instantiate → finish. Can't remember 12 steps? Grab three key nodes: ⑤ BFPP, ⑥ BPP, ⑪ finishBeanFactoryInitialization .
Interview killer : ⑤ and ⑥ order cannot reverse — first collect all BeanDefinitions (⑤), then know which BPPs to register (⑥).
Following ⑤⑥, must understand BFPP vs BPP difference, interview favorite:
Handles : BFPP → BeanDefinition (metadata); BPP → Bean instance.
Timing : BFPP → Container startup, before bean creation; BPP → Before/after each bean initialization.
Frequency : BFPP → Once; BPP → Twice per bean (before/after).
Typical impl : BFPP → ConfigurationClassPostProcessor; BPP → AutowiredAnnotationBeanPostProcessor.
Can replace bean : BFPP → No; BPP → Yes (can return proxy).
One-liner: BFPP changes "blueprint", BPP changes "product" .
BPP interface is plain with only two default methods:
public interface BeanPostProcessor {
@Nullable
default Object postProcessBeforeInitialization(Object bean, String beanName) { return bean; }
@Nullable
default Object postProcessAfterInitialization(Object bean, String beanName) { return bean; }
}One astonishing fact : @Autowired injection relies on AutowiredAnnotationBeanPostProcessor; @Async, @Transactional proxies rely on AbstractAutoProxyCreator — Spring's user-facing advanced features are almost all BeanPostProcessor products . Understanding this explains why Spring is so extensible.
6.4 spring-aop: When Exactly Is Proxy Born?
Positioning : Dynamic proxy-based aspect implementation, provides underlying proxy capability for transactions, caching, logging, security. Package structure:
org.springframework.aop/
├── framework/ # Proxy framework core
│ ├── ProxyFactory.java # Proxy factory (unified entry)
│ ├── AopProxy.java # Proxy interface
│ ├── JdkDynamicAopProxy.java # JDK dynamic proxy impl
│ └── CglibAopProxy.java # CGLIB proxy impl
├── aop/advice/ # Advice types: Before / AfterReturning / Throws / MethodInterceptor
├── aspectj/ # AspectJ annotation support, expression pointcuts
└── config/ # @EnableAspectJAutoProxyInterview must-ask: When is AOP proxy object created? Answer all hidden in this class — it's itself a BeanPostProcessor:
// spring-aop: AbstractAutoProxyCreator
@Override
public Object postProcessAfterInitialization(@Nullable Object bean, String beanName) {
if (bean != null) {
Object cacheKey = getCacheKey(bean.getClass(), beanName);
// If circular dependency phase already proxied early, don't proxy again
if (this.earlyProxyReferences.remove(cacheKey) != bean) {
return wrapIfNecessary(bean, beanName, cacheKey); // Switch cat for prince
}
}
return bean;
}
protected Object wrapIfNecessary(Object bean, String beanName, Object cacheKey) {
// 1. Get all matching interceptors (advices) for this bean
Object[] specificInterceptors = getAdvicesAndAdvisorsForBean(bean.getClass(), beanName, null);
// 2. If interceptors exist, create proxy object replacing original
if (specificInterceptors != DO_NOT_PROXY) {
return createProxy(bean.getClass(), beanName, specificInterceptors,
new SingletonTargetSource(bean));
}
return bean;
}Key point : AOP proxy created after bean initialization completes, by BPP post-process; not at object instantiation.
JDK or CGLIB? Selection rule just three lines:
// DefaultAopProxyFactory#createAopProxy
if (config.isOptimize() || config.isProxyTargetClass() || hasNoUserSuppliedProxyInterfaces(config)) {
return new ObjenesisCglibAopProxy(config); // CGLIB: class without interface / forced proxyTargetClass
}
return new JdkDynamicAopProxy(config); // JDK: target implements interfaceTwo proxy ways comparison:
Principle : JDK — interface-based; CGLIB — inheritance-based (bytecode generates subclass).
Requirement : JDK — target class must implement interface; CGLIB — class cannot be final.
Performance : JDK — direct forwarding, faster; CGLIB — bytecode manipulation, generation slower.
Proxy class name : JDK — com.sun.proxy.$ProxyXX; CGLIB — Xxx$$EnhancerBySpringCGLIB$$XXXX.
Force switch : @EnableAspectJAutoProxy(proxyTargetClass = true); Spring 7 / Boot 2.x+ default choice.
Version note : Classic rule "interface prefers JDK proxy", but Spring 7 and Spring Boot 2.x+ default to unified CGLIB ( spring.aop.proxy-target-class=true ), greatly simplifying this question. Can't tell if injected is raw or proxy? Direct System.out.println(bean.getClass()) , or use AopUtils.isAopProxy() / isJdkDynamicProxy() to judge.
After proxy created, how are method calls intercepted? Look at JDK proxy interception entry, chain of responsibility clear:
// JdkDynamicAopProxy#invoke (excerpt)
@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
Object target = this.advised.targetSource.getTarget();
// Get interceptor chain
List<Object> chain = this.advised.getInterceptorsAndDynamicInterceptionAdvice(method, targetClass);
if (chain.isEmpty()) {
// No interceptors, direct reflective call target method
return AopUtils.invokeJoinpointUsingReflection(target, method, args);
}
// Has interceptors, recursively walk chain
MethodInvocation invocation = new ReflectiveMethodInvocation(proxy, target, method, args, targetClass, chain);
return invocation.proceed();
}Interceptor chain core interface is MethodInterceptor (around advice):
public interface MethodInterceptor extends Advice {
Object invoke(MethodInvocation invocation) throws Throwable;
}Technical highlight : Chain it all — @EnableAspectJAutoProxy → registers AnnotationAwareAspectJAutoProxyCreator (BPP) → refresh() step ⑥ in place → step ⑪ creates each bean → initializeBean callback → proxy born . Multiple Advisors form interceptor chain recursive execution, perfect combo of "Chain of Responsibility + Proxy pattern". This also explains why transactions must go through AOP : TransactionInterceptor itself is an Advice ; @Transactional "magic" = one method interceptor. Next section sees it.
6.5 spring-tx: @Transactional's Behind-the-Scenes Manipulator
Positioning : Transaction abstraction layer, shields differences between transaction APIs, provides declarative transaction capability. Package structure:
org.springframework.transaction/
├── annotation/ # @Transactional, @TransactionalEventListener
├── config/ # @EnableTransactionManagement
├── interceptor/ # TransactionInterceptor
└── support/ # PlatformTransactionManager, TransactionStatus, TransactionDefinitionTop abstraction is PlatformTransactionManager, three methods extremely plain:
public interface PlatformTransactionManager {
TransactionStatus getTransaction(TransactionDefinition definition) throws TransactionException;
void commit(TransactionStatus status) throws TransactionException;
void rollback(TransactionStatus status) throws TransactionException;
}@Transactionalwork chain: annotation parsed by transaction aspect → proxy object generated → method call enters TransactionInterceptor → start transaction → execute business method → commit/rollback. Core code:
// TransactionInterceptor#invoke → TransactionAspectSupport#invokeWithinTransaction (excerpt)
protected Object invokeWithinTransaction(Method method, Class<?> targetClass, InvocationCallback invocation)
throws Throwable {
// 1. Read @Transactional attributes (propagation, isolation, rollbackFor)
TransactionAttributeSource tas = getTransactionAttributeSource();
TransactionAttribute txAttr = (tas != null ? tas.getTransactionAttribute(method, targetClass) : null);
// 2. Get transaction manager
PlatformTransactionManager tm = determineTransactionManager(txAttr);
// 3. Start transaction per propagation: REQUIRES_NEW/NESTED etc handled here, connection bound to current thread via ThreadLocal
TransactionInfo txInfo = createTransactionIfNecessary(tm, txAttr, joinpointIdentification);
Object retVal;
try {
retVal = invocation.proceedWithInvocation(); // 4. Execute your business method
} catch (Throwable ex) {
completeTransactionAfterThrowing(txInfo, ex); // 5. Whether rollbackFor matches, decides rollback or commit
throw ex;
} finally {
cleanupTransactionInfo(txInfo);
}
commitTransactionAfterReturning(txInfo); // 6. Normal commit
return retVal;
}Technical highlight : Through AOP interception + transaction manager abstraction + TransactionSynchronizationManager (ThreadLocal), achieves complete decoupling of business code and transaction logic; connection-thread binding also hidden here.
7 transaction propagation behaviors, interview requires reciting: Propagation.REQUIRED (default): Join existing transaction, else create new. Propagation.SUPPORTS: Join if exists, else run non-transactional. Propagation.MANDATORY: Must run in transaction, else throw exception. Propagation.REQUIRES_NEW: Always new transaction, suspend current. Propagation.NOT_SUPPORTED: Run non-transactional, suspend current. Propagation.NEVER: Cannot run in transactional environment. Propagation.NESTED: Nested transaction using savepoint.
Interview high-frequency: Transaction failure scenarios . All derivable from above code:
Symptom : @Transactional completely ineffective — Root Cause : Self-invocation ( this.xxx()) didn't go through proxy — Solution : Inject self-proxy / split into two beans / AopContext.currentProxy().
Symptom : Method non-public — Root Cause : Default aspect rule can't intercept — Solution : Make public.
Symptom : No rollback — Root Cause : Throws checked exception , default only rolls back RuntimeException / Error — Solution : @Transactional(rollbackFor = Exception.class).
Symptom : Mysterious commit — Root Cause : Method try-catch swallows exception — Solution : Re-throw, or manually
TransactionAspectSupport.currentTransactionStatus().setRollbackOnly().
Symptom : Throws UnexpectedRollbackException — Root Cause : Inner REQUIRED marked rollback-only, outer swallowed exception and returned normally — Solution : Let exception propagate / inner use REQUIRES_NEW.
Symptom : Final class/method — Root Cause : CGLIB cannot override — Solution : Remove final.
Symptom : DB engine unsupported — Root Cause : e.g., MyISAM — Solution : Switch to InnoDB.
Symptom : Missing @EnableTransactionManagement — Root Cause : Transaction aspect never registered — Solution : Add annotation.
Why same-class self-invocation fails? Because proxy only intercepts external calls; internal this call bypasses proxy, never enters TransactionInterceptor. I've debugged this in production more than once; memorize this table to save all-nighters.
6.6 spring-webmvc: One HTTP Request's Complete Journey
Positioning : Servlet-based MVC framework, core dispatch flow for HTTP requests. Package structure:
org.springframework.web.servlet/
├── DispatcherServlet.java # Front controller (core)
├── HandlerMapping.java # Request → Handler mapping
├── HandlerAdapter.java # Handler adapter
├── RequestMappingHandlerMapping.java # @RequestMapping implementation
├── ViewResolver.java # View resolver
└── config/annotation/EnableWebMvc.javaAll requests go through DispatcherServlet dispatch; core is doDispatch() — 60 lines uphold entire MVC:
// DispatcherServlet#doDispatch (excerpt)
protected void doDispatch(HttpServletRequest request, HttpServletResponse response) throws Exception {
HttpServletRequest processedRequest = checkMultipart(request); // ① Wrap multipart request
HandlerExecutionChain mappedHandler = getHandler(processedRequest); // ② Traverse HandlerMapping find handler + interceptor chain
if (mappedHandler == null) {
noHandlerFound(processedRequest, response); // 404
return;
}
HandlerAdapter ha = getHandlerAdapter(mappedHandler.getHandler()); // ③ Find adapter that can execute it
if (!mappedHandler.applyPreHandle(processedRequest, response)) { // ④ Interceptor preHandle, any false short-circuits
return;
}
ModelAndView mv = ha.handle(processedRequest, response, mappedHandler.getHandler()); // ⑤ Actually execute Controller
mappedHandler.applyPostHandle(processedRequest, response, mv); // ⑥ Interceptor postHandle (reverse order)
processDispatchResult(processedRequest, response, mappedHandler, mv, dispatchException); // ⑦ Render/write response
// ⑧ triggerAfterCompletion in finally, runs even on exception
}Complete chain diagram:
Technical highlight : Front Controller pattern + Adapter pattern . DispatcherServlet only manages flow, not implementation; all delegated to strategy interfaces — the famous nine components : HandlerMapping , HandlerAdapter , HandlerExceptionResolver , ViewResolver , LocaleResolver , ThemeResolver , MultipartResolver , FlashMapManager , and 7.0 new ApiVersionResolver . All requests unified entry; different handler types use different adapters; extensibility extremely strong.
Six modules code familiarized, next compress into interview-ready answers.
Interview High-Frequency Quick Answers
First draw Bean's life as a total diagram (suggest drawing yourself; drawing it out means you understand):
Q1: Explain Bean lifecycle?
From doGetBean() start → createBean() → ①Instantiation → ②Property population → ③Aware interface callbacks → ④BPP.before ( @PostConstruct ) → ⑤ InitializingBean.afterPropertiesSet → ⑥init-method → ⑦BPP.after (AOP proxy born here) → Use → Destruction.
Q2: When is AOP proxy created?
In BeanPostProcessor.after phase, AbstractAutoProxyCreator#postProcessAfterInitialization() calls wrapIfNecessary() to decide if proxy needed, then createProxy() creates proxy object.
Q3: How is circular dependency solved? Why three-level cache?
Three-level cache: level 1 finished product, level 2 semi-finished, level 3 factories. A creates, early exposes ObjectFactory to level 3; B injects, gets early reference from level 3. Real significance of level 3 is allow AOP proxy to intervene at early exposure stage , ensuring globally same reference; if no proxy needed level 2 suffices. Constructor injection circular dependency unsolvable because object can't be instantiated.
Q4: BeanFactory vs ApplicationContext difference?
BeanFactory is IoC bottom interface, lazy loading; ApplicationContext extends it with events, i18n, resource loading, annotation-driven, pre-instantiates singletons at startup. Daily dev uses ApplicationContext , but underlying core remains BeanFactory .
Q5: Why start reading from refresh() ?
Because it's container refresh master entry, contains BeanFactory preparation, BeanDefinition loading, BPP registration, singleton instantiation etc. Master refresh() and IoC main trunk basically clear.
Q6: What do you focus on first when reading source?
Three things: Entry classes ( AbstractApplicationContext , DispatcherServlet ), Core models ( BeanDefinition , BeanFactory ), Extension points ( BeanFactoryPostProcessor , BeanPostProcessor ). This quickly builds skeleton instead of drowning in details.
Two interview gold quotes:
Q: Spring's most core design philosophy? A : Two words — Extension points . BFPP lets you change "blueprint", BPP lets you swap "product", Aware lets you grab "container", HandlerMapping/HandlerAdapter lets you take over "dispatch". Spring's own features (AOP, transactions, validation, config binding) are all first users of these extension points, not privileged class . That's why we can plug any capability without forking source. Q: What did you gain from reading source? A : Three "no longer afraid" — no longer afraid of stack traces (one glance recognizes which BPP did it), no longer afraid of "not working" (know if proxy generated), no longer afraid of design (see how Spring uses interfaces + template method to cage complexity).
Pitfall Checklist: Roadblocks on Source Reading Path
Difficulty : Source too large, no starting point — Symptom : Open project, clueless — Solution : Scenario-driven: write minimal demo, breakpoint from refresh() entry, don't read linearly.
Difficulty : Debug jumping around, lost — Symptom : Step Into few steps into unknown class — Solution : Check Call Stack to know how you got there; Drop Frame backtrack; Method Breakpoint fixed intercept; read class/method name English semantics first.
Difficulty : Too many interfaces, can't find impl — Symptom : One interface N implementations — Solution : Ctrl+Alt+B jump impl; prioritize Default / Simple / Abstract prefixed defaults (e.g., DefaultListableBeanFactory, DataSourceTransactionManager); breakpoint check runtime actual type.
Difficulty : Lambda callbacks incomprehensible — Symptom : () -> createBean(...) unknown when executed — Solution : Breakpoint inside lambda body, check Call Stack for ObjectFactory.getObject() caller.
Difficulty : BPP trigger timing chaos — Symptom : Don't know when extension points execute — Solution : Memorize: Instantiate → Property inject → Aware → BPP.before → init → BPP.after; trace line by line in initializeBean().
Difficulty : Three-level cache dizzy — Symptom : Three Maps who promotes whom — Solution : Memorize
Factory ->(getObject)-> Semi-finished ->(init complete)-> Finished; only singleton, non-constructor injection solvable; breakpoint trace A↔B demo.
Difficulty : Proxy object unclear — Symptom : Injected raw or proxy? — Solution : println(bean.getClass()); AopUtils.isAopProxy().
Difficulty : refresh() 12 steps unmemorable — Symptom : Flow too long — Solution : Grab three keys: BFPP, BPP, finishBeanFactoryInitialization.
Difficulty : Transaction/AOP not working — Symptom : Annotation written, no effect — Solution : Self-invocation, non-public, final, swallow exception — eliminate one by one from TransactionInterceptor entry.
Difficulty : Understand but can't articulate — Symptom : Interview question, stuck — Solution : Feynman technique: close laptop, explain refresh() 12 steps to imaginary newbie; compress each module to one plain sentence.
Difficulty : Version behavior inconsistent — Symptom : 5.x/6.x/7.x materials conflict — Solution : Fix one version read through, don't read main branch.
Learning Roadmap: 9 Weeks to Master Spring Core Source
Follow this rhythm, one theme per week, 1-2 hours daily:
Week 1 : Env setup + spring-core utilities, Resource system — Goal: Independent debug env running — Hands-on: Write minimal demo, hit first breakpoint.
Week 2 : spring-beans: BeanDefinition loading, parsing, registration — Goal: Know what BeanDefinition is — Hands-on: Draw BeanDefinition registration flow.
Week 3 : spring-beans: Bean creation, dependency injection, circular dependency, three-level cache — Goal: Explain Bean creation full flow — Hands-on: Breakpoint trace doCreateBean, use A↔B demo observe cache changes.
Week 4 : spring-context: refresh() 12 steps, BFPP/BPP — Goal: Container startup flow mastered — Hands-on: Implement custom BeanPostProcessor.
Week 5 : spring-context: Event mechanism, i18n, @Configuration principle — Goal: Understand annotation-driven — Hands-on: Use ApplicationListener listen ContextRefreshedEvent.
Week 6 : spring-aop: JDK/CGLIB proxy, aspects, advices, pointcuts — Goal: Write simple AOP, explain proxy timing — Hands-on: Write an aspect, breakpoint watch wrapIfNecessary.
Week 7 : spring-tx: Transaction propagation, failure scenarios — Goal: Recite 7 propagation behaviors — Hands-on: Reproduce self-invocation failure.
Week 8 : spring-webmvc: DispatcherServlet, request processing flow — Goal: Explain one HTTP request journey — Hands-on: Breakpoint trace doDispatch.
Week 9 : String beads: draw Bean lifecycle diagram yourself — Goal: Off-script explain four main lines — Hands-on: Feynman teach someone else.
Advanced direction: Combine Spring Boot to understand @EnableAutoConfiguration and @Conditional implementation; revisit later for new insights.
Spring 7.0 New Toys: Interview Bonus Points
Since reading 7.0.8, these new features deserve standalone mention; interviewers will be impressed:
// BeanRegistrar: 7.0 new programmatic bean registration (AOT/native-image friendly)
// Must use @Import to introduce, @Bean/@Component won't trigger register()
class MyBeanRegistrar implements BeanRegistrar {
@Override
public void register(BeanRegistry registry, Environment env) {
registry.registerBean("foo", Foo.class);
registry.registerBean("bar", Bar.class, spec -> spec
.prototype().lazyInit()
.supplier(ctx -> new Bar(ctx.bean(Foo.class))));
if (env.matchesProfiles("prod")) { // Can write if/for, more flexible than @Conditional
registry.registerBean(Baz.class);
}
}
}Others in one line:
@GetMapping(path = "/{id}", version = "1.2+") // Native API versioning (path/Header/param/MediaType four strategies)
@Retryable @ConcurrencyLimit(10) // Core resilience (with @EnableResilientMethods, replaces spring-retry)
@ImportHttpServices(group = "weather") // HTTP client group config
RestTestClient // 7.0 new non-reactive test clientMigration red lines : javax.annotation.* / javax.inject.* completely unsupported, must migrate to jakarta.* ; spring-jcl removed; Jackson 3 promoted (Jackson 2 deprecated); RestTemplate doc-level deprecated, 7.1 will add @Deprecated . When migrating old projects to Boot 4, self-check these first.
Closing: Internalize the Skeleton
Reading source is slow work; don't expect full mastery in weeks. 1-2 hours daily, persist two months, your Spring understanding will transform. Compress full text to 30 seconds:
Version : Spring Framework 7.0.8 (Spring Boot 4.x underlying), runtime JDK 17+, compile JDK 25 Deep-read 6 modules : core / beans / context / aop / tx / webmvc — sufficient, deep, widest interview coverage Method : Scenario-driven + breakpoint trace call chains + three-pass reading, skip compatibility noise Two must-memorize entries : AbstractApplicationContext#refresh() and AbstractAutowireCapableBeanFactory#doCreateBean() One total diagram : BeanDefinition (blueprint) → ⑤ BFPP collect → Instantiate → Populate → Initialize (BPP → AOP proxy born) → Finished into singleton pool
Landing advice three: today just set up env (don't just bookmark); breakpoint from refresh() first pass; draw a diagram after each module.
For questions about attribution, corrections or content rights, please contactand we will review it promptly.