Build Your Own Spring IoC Container: From Core Principles to Circular Dependency Resolution
This article guides you through building a minimal Spring IoC container from scratch, covering BeanDefinition metadata, BeanFactory design, full bean lifecycle, three-level cache for circular dependencies, BeanPostProcessor for AOP extension points, with runnable code and interview Q&A.
Core Essence
Spring's core is IoC (Inversion of Control) and DI (Dependency Injection) . Implementing these two features first, then extending lifecycle and extension points, yields a clear architecture covering core interview topics.
Core Architecture Design
A Spring container is essentially a Bean factory managing the full bean lifecycle. The minimal architecture consists of: BeanDefinition: Stores bean metadata (class name, scope, dependencies, init method, etc.) BeanDefinitionRegistry: Registry for bean definitions, handling registration and lookup BeanFactory: Core container interface defining
getBean()DefaultListableBeanFactory: Default container implementation integrating all functionality
Step-by-Step Implementation
1. Define Bean Metadata: BeanDefinition
public class BeanDefinition {
// Bean class name
private String beanClassName;
// Whether singleton (default true)
private boolean singleton = true;
// Dependent bean names
private List<String> dependsOn = new ArrayList<>();
// Initialization method name
private String initMethodName;
// getters/setters omitted
}2. Define Core Container Interface: BeanFactory
public interface BeanFactory {
// Get bean instance by name
Object getBean(String beanName) throws Exception;
}3. Implement Core Container: DefaultListableBeanFactory
Heart of the container, implemented in three steps:
public class DefaultListableBeanFactory implements BeanFactory, BeanDefinitionRegistry {
// 1. Bean definition registry: stores all bean metadata
private final Map<String, BeanDefinition> beanDefinitionMap = new ConcurrentHashMap<>();
// 2. Singleton pool: stores all singleton bean instances
private final Map<String, Object> singletonObjects = new ConcurrentHashMap<>();
// Register bean definition
@Override
public void registerBeanDefinition(String beanName, BeanDefinition beanDefinition) {
beanDefinitionMap.put(beanName, beanDefinition);
}
// Core getBean method
@Override
public Object getBean(String beanName) throws Exception {
// Step 1: Check singleton pool first
Object singletonBean = singletonObjects.get(beanName);
if (singletonBean != null) {
return singletonBean;
}
// Step 2: Get bean definition, reflectively create instance
BeanDefinition bd = beanDefinitionMap.get(beanName);
if (bd == null) {
throw new RuntimeException("Bean not found: " + beanName);
}
Object bean = Class.forName(bd.getBeanClassName()).newInstance();
// Step 3: Dependency injection (autowiring)
populateBean(bean, bd);
// Step 4: Initialization callback
initializeBean(bean, bd);
// Step 5: If singleton, put into singleton pool
if (bd.isSingleton()) {
singletonObjects.put(beanName, bean);
}
return bean;
}
}4. Implement Dependency Injection: populateBean Method
private void populateBean(Object bean, BeanDefinition bd) throws Exception {
// Iterate all dependent beans, recursively get and inject
for (String dependBeanName : bd.getDependsOn()) {
Object dependBean = getBean(dependBeanName);
// Simple implementation: inject by field name (real Spring supports by-type, constructor injection)
Field field = bean.getClass().getDeclaredField(dependBeanName);
field.setAccessible(true);
field.set(bean, dependBean);
}
}5. Implement Initialization Callback: initializeBean Method
private void initializeBean(Object bean, BeanDefinition bd) throws Exception {
// 1. Execute InitializingBean interface's afterPropertiesSet method
if (bean instanceof InitializingBean) {
((InitializingBean) bean).afterPropertiesSet();
}
// 2. Execute custom init-method
if (bd.getInitMethodName() != null && !bd.getInitMethodName().isEmpty()) {
Method initMethod = bean.getClass().getMethod(bd.getInitMethodName());
initMethod.invoke(bean);
}
}Usage Demo
public class Main {
public static void main(String[] args) throws Exception {
// 1. Create container
DefaultListableBeanFactory factory = new DefaultListableBeanFactory();
// 2. Register UserService bean definition
BeanDefinition userServiceBd = new BeanDefinition();
userServiceBd.setBeanClassName("com.example.UserService");
userServiceBd.getDependsOn().add("userDao");
factory.registerBeanDefinition("userService", userServiceBd);
// 3. Register UserDao bean definition
BeanDefinition userDaoBd = new BeanDefinition();
userDaoBd.setBeanClassName("com.example.UserDao");
factory.registerBeanDefinition("userDao", userDaoBd);
// 4. Get bean, auto-completes dependency injection
UserService userService = (UserService) factory.getBean("userService");
userService.getUser(); // Normal call, UserDao already injected
}
}Advanced Optimization Points
If time permits, extend the following features — also common interviewer follow-ups:
Circular Dependency Handling : Expose uninitialized bean instances early via "three-level cache"
Scope Extension : Implement prototype, request, session scopes
BeanPostProcessor Extension Point : Allow custom processing before/after bean initialization
Annotation Support : Implement @Component, @Autowired scanning and injection
Destruction Callbacks : Implement DisposableBean interface and destroy-method
Interviewer High-Frequency Follow-ups
Gap between handwritten container and real Spring : Real Spring includes AOP, transactions, events, i18n, resource loading, plus extensive optimizations for performance, concurrency safety, and exception handling.
Why Spring uses three-level cache for circular dependencies : Level 1 caches fully initialized beans, level 2 caches early (half-initialized) beans, level 3 caches bean factories. Only when AOP proxying is needed does level 3 generate the proxy, avoiding premature proxy creation.
Stages of a bean's complete lifecycle : Instantiation → Dependency Injection → Pre-initialization (BeanPostProcessor) → Initialization → Post-initialization → Usage → Destruction.
Complete Core Code & Technical Highlights Analysis
1. Basic Interface Definitions (Contract First, Implementation Later)
// Bean definition registry interface
public interface BeanDefinitionRegistry {
void registerBeanDefinition(String beanName, BeanDefinition beanDefinition);
BeanDefinition getBeanDefinition(String beanName);
}
// Initialization callback interface
public interface InitializingBean {
void afterPropertiesSet() throws Exception;
}
// Bean post-processor (soul of Spring extensibility)
public interface BeanPostProcessor {
default Object postProcessBeforeInitialization(Object bean, String beanName) throws Exception {
return bean;
}
default Object postProcessAfterInitialization(Object bean, String beanName) throws Exception {
return bean;
}
}2. Complete Core Container Implementation (Runnable)
public class DefaultListableBeanFactory implements BeanFactory, BeanDefinitionRegistry {
// ==================== Core Caches ====================
// 1. Bean definition registry: stores all bean metadata
private final Map<String, BeanDefinition> beanDefinitionMap = new ConcurrentHashMap<>(256);
// 2. Singleton pool: stores fully initialized beans (level 1 cache)
private final Map<String, Object> singletonObjects = new ConcurrentHashMap<>(256);
// 3. Post-processor registry: stores all BeanPostProcessor instances
private final List<BeanPostProcessor> beanPostProcessors = new CopyOnWriteArrayList<>();
// ==================== Technical Highlight 1: Elegant Extension Point Design ====================
public void addBeanPostProcessor(BeanPostProcessor postProcessor) {
beanPostProcessors.add(postProcessor);
}
// ==================== Technical Highlight 2: Lazy Loading + Thread-Safe getBean ====================
@Override
public Object getBean(String beanName) throws Exception {
// Fast check: if already in singleton pool, return directly
Object singleton = singletonObjects.get(beanName);
if (singleton != null) {
return singleton;
}
// Double-checked locking: prevent concurrent duplicate bean creation
synchronized (singletonObjects) {
singleton = singletonObjects.get(beanName);
if (singleton != null) {
return singleton;
}
return createBean(beanName, beanDefinitionMap.get(beanName));
}
}
// ==================== Technical Highlight 3: Clear Bean Lifecycle Decomposition ====================
private Object createBean(String beanName, BeanDefinition bd) throws Exception {
// Phase 1: Instantiate bean (allocate memory)
Object bean = instantiateBean(bd);
// Phase 2: Dependency injection (populate properties)
populateBean(bean, bd);
// Phase 3: Initialization (execute callbacks and post-processors)
bean = initializeBean(bean, beanName, bd);
// Phase 4: Put into singleton pool
if (bd.isSingleton()) {
singletonObjects.put(beanName, bean);
}
return bean;
}
private Object instantiateBean(BeanDefinition bd) throws Exception {
// Simple implementation: no-arg constructor instantiation
return Class.forName(bd.getBeanClassName()).getDeclaredConstructor().newInstance();
}
private void populateBean(Object bean, BeanDefinition bd) throws Exception {
// Autowire dependencies by field name
for (String dependBeanName : bd.getDependsOn()) {
Object dependBean = getBean(dependBeanName);
Field field = bean.getClass().getDeclaredField(dependBeanName);
field.setAccessible(true);
field.set(bean, dependBean);
}
}
// ==================== Technical Highlight 4: Standard Initialization Flow ====================
private Object initializeBean(Object bean, String beanName, BeanDefinition bd) throws Exception {
// 1. Execute pre-initialization post-processors
Object wrappedBean = bean;
for (BeanPostProcessor processor : beanPostProcessors) {
wrappedBean = processor.postProcessBeforeInitialization(wrappedBean, beanName);
}
// 2. Execute InitializingBean callback
if (wrappedBean instanceof InitializingBean) {
((InitializingBean) wrappedBean).afterPropertiesSet();
}
// 3. Execute custom init-method
if (bd.getInitMethodName() != null && !bd.getInitMethodName().isEmpty()) {
Method method = wrappedBean.getClass().getMethod(bd.getInitMethodName());
method.invoke(wrappedBean);
}
// 4. Execute post-initialization post-processors (AOP proxy generated here!)
for (BeanPostProcessor processor : beanPostProcessors) {
wrappedBean = processor.postProcessAfterInitialization(wrappedBean, beanName);
}
return wrappedBean;
}
// BeanDefinitionRegistry implementation
@Override
public void registerBeanDefinition(String beanName, BeanDefinition beanDefinition) {
beanDefinitionMap.put(beanName, beanDefinition);
}
@Override
public BeanDefinition getBeanDefinition(String beanName) {
return beanDefinitionMap.get(beanName);
}
}3. Key Technical Highlights Summary
Interface/Implementation Separation : Define contracts (BeanFactory, BeanDefinitionRegistry) first, then provide default implementation. Counterpart: Spring's interface-oriented programming, enabling swappable container implementations.
Double-Checked Locking + ConcurrentHashMap : Ensures thread-safe bean creation in multi-threaded environments while maintaining performance. Counterpart: Spring's singleton bean creation thread-safety mechanism.
Lifecycle Phase Decomposition : Split bean creation into instantiation → dependency injection → initialization phases. Counterpart: Standard Spring bean lifecycle division, foundation for extension points.
BeanPostProcessor Extension Point : Allow custom logic insertion before/after bean initialization without invading core container code. Counterpart: Spring's core extension mechanism; AOP, transactions, annotation processing all build on this.
Lazy Loading Mechanism : Beans created only on first getBean() call, saving startup resources. Counterpart: Spring's default lazy-loading strategy (configurable via @Lazy).
Core Technical Difficulties & Solutions
1. Difficulty Panorama
High Frequency
↑
| * Concurrency Safety (0.4,0.6)
| * DI Extension (0.3,0.4)
| * Scope (0.5,0.5)
| * AOP Integration (0.8,0.7)
| * Circular Dependency (0.9,0.9) ← Absolute Hotspot
| * Init/Destroy (0.2,0.3)
|
└──────────────────────────────────────────→ High Difficulty
Low Difficulty2. Detailed Difficulty Coordinates
Circular Dependency : Difficulty 0.9, Frequency 0.9, Top-right (high difficulty, high frequency), Interview Heat: 🔥🔥🔥🔥🔥
AOP + IoC Integration : Difficulty 0.8, Frequency 0.7, Top-right, Interview Heat: 🔥🔥🔥🔥
Concurrency Safety : Difficulty 0.4, Frequency 0.6, Upper-left, Interview Heat: 🔥🔥🔥
Scope Implementation : Difficulty 0.5, Frequency 0.5, Center, Interview Heat: 🔥🔥
DI Extension : Difficulty 0.3, Frequency 0.4, Bottom-left (low difficulty, low frequency), Interview Heat: 🔥
Init/Destroy Order : Difficulty 0.2, Frequency 0.3, Bottom-left, Interview Heat: 🔥
3. Detailed Difficulties & Solutions
⚠️ Circular Dependency (Highest Frequency) : Problem: A depends on B, B depends on A → recursive creation causes stack overflow. Solution: Three-level cache mechanism: expose uninitialized bean instances early, separate instantiation from initialization. Core code: See Section 4 complete implementation.
⚠️ Concurrency Safety : Problem: Multiple threads calling getBean() simultaneously may create multiple identical singletons. Solution: 1. Singleton pool uses ConcurrentHashMap; 2. Double-checked locking during singleton bean creation. Core code: See Section 2 getBean() method.
⚠️ Bean Scope Implementation : Problem: prototype scope requires new instance per getBean(), must not enter singleton pool. Solution: 1. Add scope field to BeanDefinition; 2. In getBean(), decide caching based on scope. Core code: if (bd.isPrototype()) { return createBean(beanName, bd); } ⚠️ DI Extension : Problem: Initial implementation only supports field-name injection; real Spring supports constructor, by-type injection. Solution: 1. Extend BeanDefinition to store constructor args; 2. Add AutowiredAnnotationBeanPostProcessor to handle @Autowired annotation. Core code: Parse @Autowired, match beans by type.
⚠️ Init/Destroy Order : Problem: Dependent beans must initialize first; on destruction, depended-upon beans must be destroyed last. Solution: 1. Recursively create dependency beans during injection; 2. Maintain destruction order linked list, execute in reverse. Core code: Record bean dependency graph, topological sort.
⚠️ AOP + IoC Integration : Problem: AOP proxy object must replace original bean in container. Solution: Generate proxy in BeanPostProcessor.postProcessAfterInitialization. Core code:
public Object postProcessAfterInitialization(Object bean, String beanName) { return createProxy(bean); }4. Highest Difficulty: Complete Three-Level Cache Circular Dependency Implementation
public class DefaultListableBeanFactory implements BeanFactory, BeanDefinitionRegistry {
// Level 1 cache: fully initialized beans (finished products)
private final Map<String, Object> singletonObjects = new ConcurrentHashMap<>(256);
// Level 2 cache: early beans (instantiated but not initialized — half-finished)
private final Map<String, Object> earlySingletonObjects = new ConcurrentHashMap<>(16);
// Level 3 cache: bean factories (for generating AOP proxies)
private final Map<String, ObjectFactory<?>> singletonFactories = new ConcurrentHashMap<>(16);
@Override
public Object getBean(String beanName) throws Exception {
// Check three caches in order
Object singleton = getSingleton(beanName);
if (singleton != null) {
return singleton;
}
synchronized (singletonObjects) {
singleton = getSingleton(beanName);
if (singleton != null) {
return singleton;
}
return createBean(beanName, beanDefinitionMap.get(beanName));
}
}
private Object getSingleton(String beanName) {
// 1. Check level 1 (finished)
Object singleton = singletonObjects.get(beanName);
if (singleton != null) {
return singleton;
}
// 2. Check level 2 (early half-finished)
singleton = earlySingletonObjects.get(beanName);
if (singleton != null) {
return singleton;
}
// 3. Check level 3 (factory)
ObjectFactory<?> factory = singletonFactories.get(beanName);
if (factory != null) {
singleton = factory.getObject();
// Move from level 3 to level 2
singletonFactories.remove(beanName);
earlySingletonObjects.put(beanName, singleton);
return singleton;
}
return null;
}
private Object createBean(String beanName, BeanDefinition bd) throws Exception {
// 1. Instantiate bean
Object bean = instantiateBean(bd);
// 2. Expose early to level 3 cache (KEY to solving circular dependency!)
if (bd.isSingleton()) {
singletonFactories.put(beanName, () -> getEarlyBeanReference(bean, beanName));
}
// 3. Dependency injection (if circular dependency occurs, fetch early-exposed bean from level 3)
populateBean(bean, bd);
// 4. Initialization
bean = initializeBean(bean, beanName, bd);
// 5. Move from level 2/3 to level 1
if (bd.isSingleton()) {
singletonObjects.put(beanName, bean);
earlySingletonObjects.remove(beanName);
singletonFactories.remove(beanName);
}
return bean;
}
// Generate early-exposed bean reference (if AOP proxy needed, generate here)
protected Object getEarlyBeanReference(Object bean, String beanName) {
Object exposedObject = bean;
for (BeanPostProcessor processor : beanPostProcessors) {
if (processor instanceof SmartInstantiationAwareBeanPostProcessor) {
exposedObject = ((SmartInstantiationAwareBeanPostProcessor) processor)
.getEarlyBeanReference(exposedObject, beanName);
}
}
return exposedObject;
}
}
// Post-processor interface supporting early proxy exposure
public interface SmartInstantiationAwareBeanPostProcessor extends BeanPostProcessor {
Object getEarlyBeanReference(Object bean, String beanName) throws Exception;
}Three-Level Cache Core Principles:
Only singleton beans support circular dependency (prototype scope does not)
After instantiation, immediately place bean factory into level 3 cache to expose reference early
When circular dependency occurs, fetch bean from level 3 cache (generate AOP proxy here if needed)
After initialization, move bean from level 2/3 caches to level 1, ensuring the same object is returned
The above covers the core code and all key technical difficulty solutions for handwriting a Spring container. The most important takeaway is not writing a complete framework, but understanding its core design philosophy: decouple object creation and usage via factory pattern, guarantee framework flexibility via extension point mechanism .
Real Interview Simulation
The article includes a simulated interview dialogue demonstrating how to explain the design. Key points from the simulation:
Container essence: large Map + reflection factory . Core flow: Package Scan → Encapsulate Definition → Instantiate → Inject Dependencies → Put into Singleton Pool. BeanDefinition stores metadata (beanName, beanClass, scope) — configuration-instance separation.
Component scanning via ClassLoader resource loading + recursive file traversal to find .class files, check for @Component, generate BeanDefinition.
Object creation on getBean(): reflective instantiation via no-arg constructor, then property injection by iterating fields with @Autowired, recursively calling getBean() for dependencies. BeanPostProcessor interface with postProcessBeforeInitialization and postProcessAfterInitialization provides AOP extension hook; proxy returned in post-processor replaces original bean.
Circular dependency solved by three-level cache: singletonObjects (level 1), earlySingletonObjects (level 2), singletonFactories (level 3). Flow: instantiate A, put factory in level 3; inject A needs B → create B; inject B needs A → get early reference from level 3, move to level 2; B completes, A gets B, moves to level 1. Only solves singleton setter injection; constructor injection unsolvable.
Container backbone: MiniApplicationContext with beanDefinitionMap, three-level cache maps, beanPostProcessors list; exposes only scan() and getBean().
Technical Highlight Code Segments
1. Annotation-Based Scanning + Recursive .class Discovery
public void scan(String basePackage) {
String path = basePackage.replace('.', '/');
Enumeration<URL> resources = Thread.currentThread()
.getContextClassLoader().getResources(path);
while (resources.hasMoreElements()) {
File dir = new File(resources.nextElement().getFile());
for (File file : dir.listFiles()) {
if (file.getName().endsWith(".class")) {
String className = basePackage + "."
+ file.getName().replace(".class", "");
Class<?> clazz = Class.forName(className);
if (clazz.isAnnotationPresent(Component.class)) {
Component comp = clazz.getAnnotation(Component.class);
String beanName = comp.value().isEmpty() ?
toLowerCaseFirst(clazz.getSimpleName()) : comp.value();
beanDefinitionMap.put(beanName,
new BeanDefinition(beanName, clazz, resolveScope(clazz)));
}
}
}
}
}Highlight: Bypass framework, directly use ClassLoader physical scanning — consistent with Spring 1.0 approach.
2. Three-Level Cache Solving Circular Dependency
public Object getBean(String beanName) {
// 1. Check level 1 (finished)
Object singleton = singletonObjects.get(beanName);
if (singleton != null) return singleton;
// 2. Check level 2 (early half-finished, solves circular dependency)
singleton = earlySingletonObjects.get(beanName);
if (singleton != null) return singleton;
// 3. Check level 3 (factory) → generate early object, put into level 2
ObjectFactory<?> factory = singletonFactories.get(beanName);
if (factory != null) {
singleton = factory.getObject();
earlySingletonObjects.put(beanName, singleton);
singletonFactories.remove(beanName);
return singleton;
}
// 4. None found, truly create
BeanDefinition bd = beanDefinitionMap.get(beanName);
return createBean(beanName, bd);
}3. Bean Creation Flow with Embedded BeanPostProcessor
private Object createBean(String beanName, BeanDefinition bd) {
// Instantiate
Object instance = bd.getBeanClass().getDeclaredConstructor().newInstance();
// Pre-processing (AOP entry point 1)
for (BeanPostProcessor bpp : beanPostProcessors) {
instance = bpp.postProcessBeforeInitialization(instance, beanName);
}
// If singleton, expose factory to level 3 first (solves circular dependency)
if (bd.isSingleton()) {
singletonFactories.put(beanName, () -> instance);
}
// Property injection
populateBean(beanName, instance);
// Post-processing (AOP entry point 2, can return proxy)
for (BeanPostProcessor bpp : beanPostProcessors) {
instance = bpp.postProcessAfterInitialization(instance, beanName);
}
if (bd.isSingleton()) {
singletonObjects.put(beanName, instance);
earlySingletonObjects.remove(beanName);
singletonFactories.remove(beanName);
}
return instance;
}4. Property Injection (Core DI)
private void populateBean(String beanName, Object instance) {
for (Field field : instance.getClass().getDeclaredFields()) {
if (field.isAnnotationPresent(Autowired.class)) {
String dependName = field.getName(); // Simplified: use field name as beanName
Object dependBean = getBean(dependName); // Recursively resolve dependency
field.setAccessible(true);
field.set(instance, dependBean);
}
}
}5. BeanPostProcessor Interface (AOP Extension Hook)
public interface BeanPostProcessor {
default Object postProcessBeforeInitialization(Object bean, String beanName) {
return bean;
}
default Object postProcessAfterInitialization(Object bean, String beanName) {
return bean;
}
}Technical Difficulties & Solutions
Package Scan Generality : Problem: Cross-platform class file scanning; direct File ops fail in JARs. Solution: Check URL protocol: file protocol uses file recursion; jar protocol uses JarFile parsing, or simplified ClassPathScanningCandidateComponentProvider (JAR ignored for brevity).
Circular Dependency Deadlock : Problem: A→B, B→A mutual wait → StackOverflow. Solution: Three-Level Cache + Early Exposure : After instantiation, put factory into level 3; before property injection, early reference available. Constructor injection unsolvable, throw BeanCurrentlyInCreationException.
DI Type Matching : Problem: Multiple same-type beans; field-name matching alone causes errors. Solution: Use @Autowired + @Qualifier to specify name, fallback to type inference, finally introduce List<BeanDefinition> for type filtering. Simplified here to show principle.
Seamless AOP Proxy Injection : Problem: Dynamic proxy replaces original bean, yet container must remain transparent. Solution: Via BeanPostProcessor.postProcessAfterInitialization return proxy; proxy stored in level 1 cache, container unaware.
Thread Safety & Performance : Problem: Multi-threaded getBean may create multiple singletons. Solution: Use ConcurrentHashMap for caches; synchronize singleton creation block with synchronized or double-checked locking, ensuring single creation.
Final Summary
Core code focuses on Scan → Three-Level Cache → DI → BPP ; each segment can be explained independently.
Difficulties cover Circular Dependency, Proxy Injection, Type Injection, Concurrency Safety — answering these scores high in interviews.
Use flowcharts and tables during explanation to show structured thinking at a glance.
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.
