Spring 7.0.8 Source Code Deep Dive: IoC, AOP, Transactions & Circular Dependencies Explained
This article analyzes Spring Framework 7.0.8 source code to explain IoC container startup, AOP proxy creation, transaction management, and circular dependency resolution via three-level cache, with code examples and interview-focused insights.
Real Interview Scenarios: Knowing vs Understanding
The article opens with real interview scenarios where candidates fail when asked follow-up questions like "When is the proxy object generated in the bean lifecycle?" or "Why must the cache be three levels, not two?" Memorizing answers only covers "what"; source code knowledge explains "why" by reconstructing call chains.
Why Read Source Code? Immediate Returns
Interview Leverage : Upgrade from "three-level cache" to "why three levels and when it fails"
Troubleshooting : Locate root causes of transaction failures, AOP not working, BeanCurrentlyInCreationException in minutes
Design Intuition : Spring as living design pattern textbook: Template Method (refresh()), Strategy (AopProxy), Factory (ObjectFactory), Chain of Responsibility (interceptor chain), Observer (events)
One Leads to Hundred : Spring Boot, Cloud, Security all share the same core mechanisms
Core skeleton (container startup, three-level cache, AOP proxy) has barely changed from Spring 5.x to 7.0.8. Learning once serves for years.
Version Baseline: Spring Framework 7.0.8 (Spring Boot 4.x, JDK 17+)
Key 7.0.8 Changes
JDK 17 baseline, JDK 25 recommended : Virtual threads, structured concurrency
Jakarta EE 11 : Servlet 6.1, Validation 3.1, Persistence 3.2
Global default CGLIB proxy : Aligned with Spring Boot, @Async behavior unified
@Proxyable annotation : Per-bean proxy strategy, can explicitly fall back to JDK proxy
BeanRegistrar API : Programmatic bean registration
Built-in retry : @Retryable, @ConcurrencyLimit in core, no spring-retry needed
JSpecify null-safety : @Nullable/@NonNull standardized
Native API versioning : Framework-level REST API versioning
HTTP Interface Client : Auto-register HTTP interface clients
Jackson 3 migration : Package com.fasterxml.jackson → tools.jackson
AOT/GraalVM native image mature : Startup speed, memory optimized
Two 7.0.8-specific notes: security fix for 16 CVEs (SpEL, SSRF, WebSocket, Multipart); SpEL operand limit default 10,000 (configurable via SpelParserConfiguration). Removed: spring-jcl, javax.annotation/inject, Undertow, Jackson 2 deprecated.
Source Code Module Map
Focus on four packages: spring-beans (BeanDefinition, DefaultListableBeanFactory), spring-context (ApplicationContext, refresh()), spring-aop (dynamic proxy), spring-tx (@Transactional). Four key classes to trace: AbstractApplicationContext, DefaultListableBeanFactory, AbstractAutoProxyCreator, TransactionInterceptor.
Deep Dive 1: IoC Container — The Heart
IoC Essence
IoC essence: centralize object creation, assembly, lifecycle management into a registry. @Component/@Bean are just metadata; real objects are created inside refresh().
Analogy: BeanDefinition = blueprint, Bean = house, BeanFactory = construction crew. BeanFactory vs ApplicationContext: lazy vs eager loading, basic vs extended (i18n, events, AOP). Core registry is DefaultListableBeanFactory with ConcurrentHashMap<String, BeanDefinition>.
refresh() 12-Step Pipeline
// AbstractApplicationContext.refresh() skeleton
synchronized (startupShutdownMonitor) {
prepareRefresh(); // ①
ConfigurableListableBeanFactory bf = obtainFreshBeanFactory(); // ②
prepareBeanFactory(bf); // ③
try {
postProcessBeanFactory(bf); // ④ extension point
invokeBeanFactoryPostProcessors(bf); // ⑤ 🔥 parse @Configuration, @ComponentScan
registerBeanPostProcessors(bf); // ⑥ 🔥 register BPPs (Autowired, AOP)
initMessageSource(); // ⑦
initApplicationEventMulticaster(); // ⑧
onRefresh(); // ⑨
registerListeners(); // ⑩
finishBeanFactoryInitialization(bf); // ⑪ 🔥🔥 instantiate all singletons
finishRefresh(); // ⑫
} catch (BeansException ex) {
destroyBeans(); cancelRefresh(ex); throw ex;
} finally { resetCommonCaches(); }
}Three critical steps: ⑤ BeanFactoryPostProcessor (ConfigurationClassPostProcessor scans @ComponentScan, @Bean, @Import), ⑥ BeanPostProcessor registration (AutowiredAnnotationBeanPostProcessor, AnnotationAwareAspectJAutoProxyCreator), ⑪ singleton instantiation (AOP proxy creation, circular dependency resolution happen here). Mnemonic: "⑤ collect blueprints, ⑥ prepare tools, ⑪ actually build houses."
Bean Lifecycle: From Raw Object to Finished Product
Creation chain: getBean() → doGetBean() → createBean() → doCreateBean(). Core in doCreateBean():
// doCreateBean main flow
BeanWrapper wrapper = createBeanInstance(beanName, mbd, args); // ① instantiate raw object
Object bean = wrapper.getWrappedInstance();
boolean earlySingletonExposure = (mbd.isSingleton()
&& this.allowCircularReferences
&& isSingletonCurrentlyInCreation(beanName));
if (earlySingletonExposure) {
// ⭐ put into L3 cache: factory, not object!
addSingletonFactory(beanName, () -> getEarlyBeanReference(beanName, mbd, bean));
}
Object exposedObject = bean;
populateBean(beanName, mbd, wrapper); // ③ property injection (may recurse → circular dep)
exposedObject = initializeBean(beanName, exposedObject, mbd); // ④ init + AOP proxy
if (earlySingletonExposure) { // ⑤ fallback check
Object earlyRef = getSingleton(beanName, false);
if (earlyRef != null) { /* replace with early ref for uniqueness */ }
}
return exposedObject;Key details: initialization hooks order (Aware → @PostConstruct → InitializingBean.afterPropertiesSet() → init-method); addSingletonFactory passes lambda (ObjectFactory) — only invoked when circular dependency actually needs early reference; constructor injection vs property injection split is the watershed for whether circular dependency can be resolved.
⚠️ allowCircularReferences defaults to true in Framework but Spring Boot 2.6+ sets it to false (spring.main.allow-circular-references=false). Same switch, two defaults — common cause of "works locally, fails in Boot".
Three Factories Distinguished
BeanFactory : Container root interface — Container's ID card
FactoryBean : Special bean type — Bean that creates beans , getObject() returns product (&name gets itself)
ObjectFactory : Functional interface — The "lazy factory" in L3 cache
Deep Dive 2: AOP — Dynamic Proxy's "Stealing Beams"
Essence
Spring AOP is NOT compile-time weaving or bytecode modification (that's AspectJ). It does one thing: after bean initialization, wrap original object with a proxy and put proxy into container. @Autowired never gets the raw new'd object — it gets the "stand-in".
Core processor: AnnotationAwareAspectJAutoProxyCreator — a BeanPostProcessor, proving "AOP is an IoC extension point."
Proxy Birthplace
// AbstractAutoProxyCreator.postProcessAfterInitialization
if (bean != null) {
Object cacheKey = getCacheKey(bean.getClass(), beanName);
if (this.earlyProxyReferences.remove(cacheKey) != bean) {
return wrapIfNecessary(bean, beanName, cacheKey); // key step: swap if needed
}
return bean;
}
protected Object wrapIfNecessary(Object bean, String beanName, Object cacheKey) {
Object[] interceptors = getAdvicesAndAdvisorsForBean(bean.getClass(), beanName, null);
if (interceptors != DO_NOT_PROXY) {
this.advisedBeans.put(cacheKey, Boolean.TRUE);
Object proxy = createProxy(bean.getClass(), beanName, interceptors, new SingletonTargetSource(bean));
this.proxyTypes.put(cacheKey, proxy.getClass());
return proxy;
}
this.advisedBeans.put(cacheKey, Boolean.FALSE);
return bean; // no matching aspect → return original
}The earlyProxyReferences.remove check prevents double proxy creation in circular dependency scenarios (foreshadowing for section 7).
JDK vs CGLIB: 7.0 Major Shift
// DefaultAopProxyFactory.createAopProxy decision logic
if (!NativeDetector.inNativeImage()
&& (config.isOptimize() || config.isProxyTargetClass()
|| hasNoUserSuppliedProxyInterfaces(config))) {
Class<?> targetClass = config.getTargetClass();
if (targetClass != null && targetClass.isInterface() && !Proxy.isProxyClass(targetClass)) {
return new JdkDynamicAopProxy(config);
}
return new ObjenesisCglibAopProxy(config); // CGLIB: generate subclass
}
return new JdkDynamicAopProxy(config);Principle : JDK Dynamic Proxy uses reflection, implements target interfaces; CGLIB uses ASM bytecode, extends target class
Requirement : JDK requires target to implement interface; CGLIB can proxy plain classes, but not final class/method
Performance : JDK fast generation, slightly faster invocation; CGLIB slow generation, fast execution
Limitation : JDK only intercepts interface methods; CGLIB intercepts non-final public/protected methods
7.x Status : JDK requires explicit @Proxyable(INTERFACES); CGLIB is global default ⭐
Spring 7.0: "Global proxy type defaulting to CGLIB — like in Spring Boot — is consistently applied to all proxy processors." Previously Boot defaulted CGLIB but native Spring processors (e.g., @Async) behaved inconsistently; 7.0 unifies to CGLIB default. CGLIB now embedded in spring-core (org.springframework.cglib), no extra dependency, performance improved. Per-bean fallback to JDK via @Proxyable(INTERFACES) or @Proxyable(interfaces = MyService.class).
Onion Model: Interceptor Chain Recursion
// ReflectiveMethodInvocation.proceed() — classic chain of responsibility
if (this.currentInterceptorIndex == this.interceptorsAndDynamicMethodMatchers.size() - 1) {
return invokeJoinpoint(); // reflectively call real method
}
Object interceptor = this.interceptorsAndDynamicMethodMatchers.get(++this.currentInterceptorIndex);
return interceptor.invoke(this); // ⭐ recursive self-call forms "onion model"JDK proxy entry point same logic. Onion: outer transaction start → middle logging → inner auth → target method → layered return → outer commit/rollback. Transaction, cache, async, retry all plug into same chain. Order controlled by @Order, Ordered, PriorityOrdered (lower value = higher priority). Approximate advice order: Before → Around → target → After → AfterReturning.
Self-Invocation Failure: Classic Pitfall
@Service
public class OrderService {
public void createOrder() {
this.pay(); // ❌ this is raw object, not proxy! Transaction won't start
}
@Transactional
public void pay() { ... }
}Root cause: proxy wraps, not replaces; this points to raw object. this.pay() bypasses proxy, interceptor chain never triggers. Three fixes (ranked): ① split into separate bean (cleanest, decouples); ② inject self (proxy injected, works but awkward); ③ AopContext.currentProxy() (needs exposeProxy=true, invasive).
Deep Dive 3: Transactions — AOP's Most Profitable Application
One-Line Essence
@Transactional = an Around Advice. Not magic: proxy intercepts via TransactionInterceptor + PlatformTransactionManager.
Core trio: PlatformTransactionManager (does open/commit/rollback), TransactionDefinition (propagation, isolation, timeout, rollback rules), TransactionInterceptor (AOP interceptor weaving logic). Plus runtime TransactionStatus (setRollbackOnly() lives here).
Execution Chain: Source Evidence
// TransactionInterceptor.invoke
return invokeWithinTransaction(invocation.getMethod(), targetClass, invocation::proceed);
// TransactionAspectSupport.invokeWithinTransaction (main flow)
TransactionAttribute txAttr = tas.getTransactionAttribute(method, targetClass); // ① parse @Transactional
TransactionManager tm = determineTransactionManager(txAttr); // ② determine TM
TransactionInfo txInfo = createTransactionIfNecessary(ptm, txAttr, "..."); // ③ open tx (get conn, disable autocommit, bind to thread)
try {
retVal = invocation.proceedWithInvocation(); // ④ execute business
} catch (Throwable ex) {
completeTransactionAfterThrowing(txInfo, ex); // ⑤ exception → rollback or commit
throw ex;
} finally {
cleanupTransactionInfo(txInfo); // ⑥ clean ThreadLocal
}
commitTransactionAfterReturning(txInfo); // ⑦ normal → commit
return retVal;DataSourceTransactionManager.doBegin() ultimately does con.setAutoCommit(false) and binds connection to TransactionSynchronizationManager's ThreadLocal so all DAOs in same thread share one connection.
Back to opening interview question: transaction requires proxy invocation. this.methodB() uses raw object, bypasses TransactionInterceptor — transaction fails. ✅ Answered.
Transaction Manager Hierarchy
PlatformTransactionManager (interface)
└─ AbstractPlatformTransactionManager
├─ DataSourceTransactionManager ← most common (JDBC/MyBatis)
├─ JpaTransactionManager
├─ HibernateTransactionManager
└─ ResourceLocalTransactionManagergetTransaction() branching: doGetTransaction() → if existing → handleExistingTransaction() per propagation; else → startTransaction() per propagation.
Propagation: 7 Types, Master 3
REQUIRED : New transaction only if none exists; shares same connection; self rolls back → outer rolls too; outer rolls back → self rolls too; mechanism: same connection
REQUIRES_NEW : Always new transaction; independent, outer suspended; self rolls back → outer unaffected; outer rolls back → self unaffected; mechanism: new connection
NESTED : Savepoint in existing; nested inside; self rolls back → rollback to savepoint; outer rolls back → self rolls too; mechanism: JDBC Savepoint
Mnemonic: REQUIRED = live/die together, REQUIRES_NEW = each for itself, NESTED = inner/outer distinct. Most business uses REQUIRED; logging/audit uses REQUIRES_NEW for independent commit; batch needing partial rollback considers NESTED.
Source shows suspend() saves current connection to SuspendedResourcesHolder, grabs new connection from pool — hence REQUIRES_NEW in loops exhausts pool (1000 records = 1000 new connections). NESTED depends on DB/driver Savepoint support; REQUIRES_NEW naturally isolated but costs connection overhead.
ThreadLocal: Transaction's Foundation
All transaction state in TransactionSynchronizationManager ThreadLocals: resources (DataSource→Connection), synchronizations, currentTransactionName, currentTransactionActive. Explains why @Transactional + new thread/@Async breaks transaction — child thread can't access parent's ThreadLocal Connection. Fix: no threads in transaction boundary; use TransactionSynchronization events or TaskDecorator + TransmittableThreadLocal for context propagation.
Transaction Failure: Categorized 9 Scenarios
1. Self-invocation : this bypasses proxy → Split class / inject self / AopContext
2. Non-public method : Spring AOP only intercepts public → Make public or AspectJ compile-time
3. final class/method : CGLIB cannot override → Remove final
4. Exception caught/swallowed : Interceptor never sees exception → Re-throw or setRollbackOnly()
5. Checked exception no rollback : Default only rolls RuntimeException/Error → rollbackFor = Exception.class
6. Wrong propagation : NOT_SUPPORTED/NEVER suspends/disables → Check propagation config
7. Class not Spring-managed : No @Service etc, no proxy → Ensure component scanning
8. DB engine unsupported : MyISAM no transactions → Use InnoDB
9. Multi-thread/@Async : Transaction bound to ThreadLocal → No threads in tx; use tx events
Three deep pits: ① Checked exceptions don't rollback by default (source: rollbackOn returns true only for RuntimeException/Error). ② Swallowed exception → UnexpectedRollbackException at commit because rollbackOnly already set; fix with REQUIRES_NEW/NESTED or don't catch. ③ REQUIRES_NEW in loop drains pool; batch/async/shorten tx scope.
7.0 New Pit: @Retryable × @Transactional Order
7.0 embeds retry (org.springframework.core.retry, @Retryable, @ConcurrencyLimit, @EnableResilientMethods). Trap: retry inside transaction method retries after rollback — wasted. Correct: retry wraps transaction (Retryable aspect outside transaction aspect) or extract remote call to separate bean.
Remember: decide "retry whole thing" first, then "open transaction".
Best Practices
@Transactional(
rollbackFor = Exception.class,
timeout = 30,
isolation = Isolation.READ_COMMITTED
)
public void transfer(Long from, Long to, BigDecimal amount) { ... }Two iron rules: don't abuse @Transactional, keep scope minimal. Long transactions (RPC, MQ, heavy compute in tx) kill connection pool — async what can be async, split what can be split, local message table for eventual consistency.
Deep Dive 4: Circular Dependency — Three-Level Cache Magic
Problem
@Component class AService { @Resource BService b; }
@Component class BService { @Resource AService a; }A needs B, B needs A. Create A → need B → create B → need A → A in creation → deadlock. Spring resolves with three-level cache.
Three Maps, No Magic
DefaultSingletonBeanRegistry fields:
L1 singletonObjects : Finished bean — Fully initialized ✅
L2 earlySingletonObjects : Early reference (half-baked, possibly proxied) — Instantiated, properties unfilled 🚧
L3 singletonFactories : ObjectFactory factory — Can produce early reference on demand 🏭
// DefaultSingletonBeanRegistry (7.0.8)
private final Map<String, Object> singletonObjects = new ConcurrentHashMap<>(256);
private final Map<String, Object> earlySingletonObjects = new ConcurrentHashMap<>(16);
private final Map<String, ObjectFactory<?>> singletonFactories = new HashMap<>(16);A↔B Full Sequence
getSingleton() lookup logic:
// getSingleton(String beanName, boolean allowEarlyReference)
Object singleton = singletonObjects.get(beanName); // 1. check L1
if (singleton == null && isSingletonCurrentlyInCreation(beanName)) {
singleton = earlySingletonObjects.get(beanName); // 2. check L2
if (singleton == null && allowEarlyReference) {
synchronized (singletonObjects) { // double-checked lock
singleton = singletonObjects.get(beanName);
if (singleton == null) {
singleton = earlySingletonObjects.get(beanName);
if (singleton == null) {
ObjectFactory<?> factory = singletonFactories.get(beanName); // 3. check L3
if (factory != null) {
singleton = factory.getObject(); // execute factory → early ref
earlySingletonObjects.put(beanName, singleton); // promote to L2
singletonFactories.remove(beanName); // remove from L3
}
}
}
}
}
}
return singleton;singletonsCurrentlyInCreation set prevents constructor cycles — throws BeanCurrentlyInCreationException.
Soul Question: Why Three Levels? Why Not Two?
Assume only L2 : instantiate B → raw B@123 → put in L2 → B fills properties, needs A → A instantiates, fills properties, gets B@123 from L2 → A finishes with B@123 → B continues init → AOP post-process → generates proxy B$Proxy@456 → B finishes, goes to L1 as B$Proxy@456. ❌ Problem: A holds B@123 (raw), not B$Proxy@456 (proxy) → transaction/AOP lost! Two identities for same bean in container.
L3 solution — stores ObjectFactory, not instance:
Step 1: instantiate B → raw B@123
Step 2: put ObjectFactory in L3: factory = () -> getEarlyBeanReference("b", mbd, B@123)
Step 3: B fills props, needs A; A fills props, needs B
Step 4: query L3 → execute factory → decide if proxy needed → generate B$Proxy@456
put in L2, return to A
Step 5: A holds B$Proxy@456 ✅
Step 6: B continues init, AOP post-process sees already proxied → reuse, no duplicateFactory callback core:
// AbstractAutowireCapableBeanFactory.getEarlyBeanReference
protected Object getEarlyBeanReference(String beanName, RootBeanDefinition mbd, Object bean) {
Object exposed = bean;
if (!mbd.isSynthetic() && hasInstantiationAwareBeanPostProcessors()) {
for (SmartInstantiationAwareBeanPostProcessor bp : getBeanPostProcessorCache().smartInstantiationAware) {
exposed = bp.getEarlyBeanReference(exposed, beanName); // AOP proxies early here
}
}
return exposed;
}
// AbstractAutoProxyCreator — earlyProxyReferences ensures "proxy once"
public Object getEarlyBeanReference(Object bean, String beanName) {
Object cacheKey = getCacheKey(bean.getClass(), beanName);
this.earlyProxyReferences.put(cacheKey, bean); // mark: early proxied
return wrapIfNecessary(bean, beanName, cacheKey);
}
public Object postProcessAfterInitialization(Object bean, String beanName) {
Object cacheKey = getCacheKey(bean.getClass(), beanName);
// ⭐ if early proxied, remove returns non-null → skip duplicate proxy
if (this.earlyProxyReferences.remove(cacheKey) != bean) {
return wrapIfNecessary(bean, beanName, cacheKey);
}
return bean;
}The earlyProxyReferences.remove() from section 5.2 couples with L3 cache — two meshed gears.
Standard interview answer: L2 solves plain object cycles but fails AOP. Early-exposing raw object makes later proxy inconsistent with early reference — injecting side loses AOP. L3 stores ObjectFactory, core value is lazy proxy generation — defer "when to proxy" to moment actually needed: no proxy needed → factory returns raw; proxy needed → factory returns proxy, earlyProxyReferences guarantees single creation. Solves cycle, preserves "AOP after init" principle, avoids premature proxy checks for all beans.
What L3 Cannot Save
Singleton setter/field injection : ✅ — Can expose early reference
Constructor injection cycle : ❌ — Object not new'd yet, nothing to expose → BeanCurrentlyInCreationException
Prototype scope : ❌ — Multi-instance bypasses singleton cache, new each getBean()
@Async bean : ⚠️ may fail — Async proxy timing special, not SmartInstantiationAwareBPP, early vs final proxy may differ
Boot 2.6+ defaults circular dependency OFF (spring.main.allow-circular-references=false), 7.0.8/Boot 4.x continues this. Three-level cache is safety net; engineering should refactor to eliminate cycles, not rely on switch.
Engineering Fixes (Priority Order)
🥇 Refactor dependency direction (extract third bean / event-driven) ← only "correct" fix
🥈 @Lazy break creation sequence ← emergency stopgap
🥉 Setter injection ← legacy compatibility
🏅 Enable spring.main.allow-circular-references ← band-aid, not medicine// 🥈 @Lazy example: injects proxy, real bean resolved on first call
@Service class OrderService {
private final PayService payService;
OrderService(@Lazy PayService payService) { this.payService = payService; }
}
// 🥇 Event decoupling: dependency direction fully broken
@Service class OrderService {
private final ApplicationEventPublisher publisher;
void create() { publisher.publishEvent(new OrderCreatedEvent(id)); }
}Technical Difficulties × Solutions Master Table
1. Circular dep + AOP intertwine : L3 ObjectFactory + earlyProxyReferences
2. Constructor cycles : @Lazy/event/extract
3. Self-invocation tx failure : split/inject/AopContext
4. Checked exception no rollback : rollbackFor=Exception
5. Swallowed exception → UnexpectedRollbackException : REQUIRES_NEW/NESTED/don't catch
6. Pool exhaustion : batch/async/shrink tx
7. Proxy type mismatch : 7.x default CGLIB, @Proxyable explicit
8. final/private unadvisable : make public non-final or AspectJ
9. Async/thread tx break : no threads in tx, use tx events
10. BPP order issues : Ordered/@Order
11. Framework vs Boot circular ref default diff : refactor not switch
12. Retry vs tx boundary : retry outside tx, extract remote call
13. Long tx : shrink scope, async, local message table
14. Init order : @DependsOn/ObjectProvider/lazy
How to Read Source Code: Pitfall Guide + 30-Day Roadmap
Avoid Five Traps
1. Million lines, where to start : Don't read linearly! One question per session, e.g., "How @Autowired injects?" → breakpoint DefaultListableBeanFactory#doResolveDependency
2. Build env fails (7.0.8 needs JDK 17+, Gradle) : JDK 21; git clone then ./gradlew :spring-core:compileJava only core module, not full build
3. Online resources all 5.x, version mismatch : Trust local 7.0.8 source as sole standard; core mechanisms stable 5→7, blogs for ideas, line numbers unreliable
4. Understand then forget in 3 days : Feynman: after reading, draw diagram/write notes from memory without looking
5. Debugger jumps everywhere, lost : Breakpoints only on skeleton methods (refresh, doGetBean, doCreateBean), use call stack for "where am I, where going"
One Mainline, Two Objects, Three Breakpoints, Four Questions
Mainline: refresh() → obtainFreshBeanFactory() → invokeBeanFactoryPostProcessors() → registerBeanPostProcessors() → finishBeanFactoryInitialization() → preInstantiateSingletons() → getBean() → doGetBean() → createBean() → doCreateBean(). Two core objects: BeanDefinition (blueprint), BeanFactory (construction crew). Three breakpoints: AbstractApplicationContext#refresh, DefaultSingletonBeanRegistry#getSingleton, AbstractAutoProxyCreator#postProcessAfterInitialization. Four driving questions: How @Component scanned? When @Autowired injected? How @Transactional becomes proxy? In circular dep, who creates first?
30-Day Roadmap
Week 1 (D1–D7) : Hand-write mini IoC: BeanDefinition + getBean + three-level cache → Acceptance: Explain refresh() 12 steps
Week 2 (D8–D14) : Trace doCreateBean, breakpoint populateBean → Acceptance: State bean's 5 lifecycle nodes
Week 3 (D15–D21) : Hand-write JDK/CGLIB proxy each; trace DefaultAopProxyFactory → Acceptance: Explain "why two-level cache fails"
Week 4 (D22–D30) : Trace TransactionInterceptor; reproduce tx failure scenarios → Acceptance: List failure checklist with antidotes
Method: don't read cover-to-cover. Use one question as hook, drill 3 layers down call stack, return. Draw diagram per flow, write Demo to verify (e.g., self-invocation failure) — beats reading 10x.
Interview Answer Template: Five-Step Method
Conclusion first : "Essence of this tech is..."
Core flow : "Core flow has X steps..."
Key design : "Most clever design is... (e.g., why three-level cache)"
Common pitfalls : "In practice watch for... (e.g., tx failure scenarios)"
Version diffs (bonus): "Spring 7.0 optimized XX..."
If asked "connect all four in five minutes": IoC reads config into BeanDefinition, refresh() step ⑪ runs "instantiate → populate → initialize", extension points all in BeanPostProcessor, AOP is one. AOP: AbstractAutoProxyCreator creates proxy post-init, calls traverse interceptor chain recursion (onion), tx/cache/async are links on same chain. Tx: @Transactional = TransactionInterceptor intercept, doBegin() = setAutoCommit(false) + ThreadLocal bind connection. Propagation 7 types, focus REQUIRED (live/die together), REQUIRES_NEW (each for itself), NESTED (Savepoint partial rollback). Biggest pits: self-invocation failure, rollbackOnly mark. Circular dep: three-level cache exposes early ref, factory lambda guarantees AOP correctness; but Boot 2.6+ defaults disabled, engineering should refactor not depend on it.
Closing
🔥 IoC manages "how to create", AOP manages "how to wrap", transactions are AOP's most profitable application, circular dependency is where these two lines knot.
Four things form one chain — any follow-up question fearless. Three actions: ① Don't memorize code, memorize call chains — interview wants you to reconstruct call chain from conclusion, not recite line numbers. ② Read source with questions, breakpoints on doCreateBean and getSingleton — 80% confusion self-resolves. ③ Actively eliminate circular deps and long transactions in engineering — mechanisms are safety nets, design is the real skill. Canned answers belong to others; source code answers belong to you.
Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
