Definition
- Inversion of Control (IoC) is a principle where the control of object creation and dependency wiring moves from your code to a framework or container.
- Spring IoC Container is the runtime that reads your configuration (annotations or XML), creates bean instances, resolves their dependencies, and manages their full lifecycle.
- ApplicationContext is the main interface for the Spring IoC container; it extends BeanFactory with features like event publishing, internationalization, and environment abstraction.
- Bean is any object that the Spring container creates, configures, and manages; you declare a class as a bean using @Component, @Service, @Repository, @Controller, or @Bean.
- Dependency Injection (DI) is the mechanism Spring uses to implement IoC; it injects required objects into a bean through constructors, setters, or fields.
Think of National Bank of India opening a new branch. Without IoC, each department (loan desk, savings desk, foreign exchange desk) goes to the market, hires its own security guard, buys its own printer, and sets up its own network connection. Every department duplicates effort and makes its own choices. With IoC, the branch manager (Spring container) sets up all shared resources centrally: one security team, one printer pool, one network. Each department declares what it needs, and the branch manager delivers it. The departments focus on banking work, not on procurement.
Understanding the Concepts
What is Inversion of Control?
Inversion of Control is a design principle where you give up control of object creation and let a container do it for you. In plain Java, when class A needs class B, you write new B() inside A. With IoC, you declare the dependency, and the Spring container creates B and passes it to A.
The word "inversion" refers to who is in control. Without IoC, your code controls the flow: it decides when to create objects and how to wire them. With IoC, the container controls the flow: it decides when to create objects, in what order, and how to connect them.
package com.bank.core;
public class InversionOfControlDemo {
public static void main(String[] args) {
System.out.println("Without IoC (traditional approach):");
System.out.println(" PaymentService creates its own NotificationService");
System.out.println(" PaymentService creates its own AuditLogger");
System.out.println(" PaymentService controls everything");
System.out.println();
System.out.println("With IoC (Spring approach):");
System.out.println(" Spring container creates NotificationService");
System.out.println(" Spring container creates AuditLogger");
System.out.println(" Spring container creates PaymentService and injects both");
System.out.println(" PaymentService just declares what it needs");
}
}
Expected output:
Without IoC (traditional approach):
PaymentService creates its own NotificationService
PaymentService creates its own AuditLogger
PaymentService controls everything
With IoC (Spring approach):
Spring container creates NotificationService
Spring container creates AuditLogger
Spring container creates PaymentService and injects both
PaymentService just declares what it needs
Why does IoC exist and why do we need it?
Without IoC, every class knows exactly which implementation it depends on. If PaymentService creates new EmailNotificationService() inside itself, you cannot swap it with SmsNotificationService without changing PaymentService code. This is tight coupling.
IoC solves three problems:
- Tight coupling: classes depend on interfaces, not concrete implementations.
- Hard to test: with
new, you cannot replace a real database call with a mock in tests. - Duplicated setup: every class that needs a database connection creates its own, instead of sharing one managed instance.
package com.bank.core;
// Problem: tight coupling without IoC
class EmailNotificationService {
public String send(String accountId, String message) {
return "Email sent to " + accountId + ": " + message;
}
}
class TightlyCoupledPaymentService {
// This class creates its own dependency. You cannot swap it.
private final EmailNotificationService notifier = new EmailNotificationService();
public String processPayment(String accountId) {
return notifier.send(accountId, "Payment processed");
}
}
public class WhyIoCExists {
public static void main(String[] args) {
var service = new TightlyCoupledPaymentService();
System.out.println(service.processPayment("SAV2001"));
System.out.println();
System.out.println("Problem: cannot replace EmailNotificationService with SMS");
System.out.println("Problem: cannot mock it in unit tests");
System.out.println("Problem: if constructor changes, every caller changes");
}
}
Expected output:
Email sent to SAV2001: Payment processed
Problem: cannot replace EmailNotificationService with SMS
Problem: cannot mock it in unit tests
Problem: if constructor changes, every caller changes
How does the Spring IoC container work internally?
When a Spring Boot application starts, the container goes through these steps:
- Component scanning: the container scans packages for classes annotated with @Component, @Service, @Repository, @Controller, or registered via @Bean methods.
- Bean definition registration: for each discovered class, the container creates a BeanDefinition object that records the class name, scope, dependencies, and init/destroy methods.
- Dependency resolution: the container builds a dependency graph. If PaymentService needs NotificationService, the container ensures NotificationService is created first.
- Instantiation: the container calls the constructor (or factory method) to create each bean.
- Injection: the container injects dependencies through constructors, setters, or fields.
- Lifecycle callbacks: the container calls @PostConstruct methods, then the bean is ready for use.
- Shutdown: on application shutdown, the container calls @PreDestroy methods.
package com.bank.core;
public class ContainerStartupSteps {
public static void main(String[] args) {
System.out.println("Spring IoC Container Startup Sequence:");
System.out.println(" Step 1: @SpringBootApplication triggers component scan");
System.out.println(" Step 2: Found @Service PaymentService");
System.out.println(" Step 3: Found @Service NotificationService");
System.out.println(" Step 4: Found @Repository AccountRepository");
System.out.println(" Step 5: Build dependency graph:");
System.out.println(" PaymentService -> NotificationService");
System.out.println(" PaymentService -> AccountRepository");
System.out.println(" Step 6: Create AccountRepository (no dependencies)");
System.out.println(" Step 7: Create NotificationService (no dependencies)");
System.out.println(" Step 8: Create PaymentService (inject both)");
System.out.println(" Step 9: Call @PostConstruct on all beans");
System.out.println(" Step 10: Application ready");
}
}
Expected output:
Spring IoC Container Startup Sequence:
Step 1: @SpringBootApplication triggers component scan
Step 2: Found @Service PaymentService
Step 3: Found @Service NotificationService
Step 4: Found @Repository AccountRepository
Step 5: Build dependency graph:
PaymentService -> NotificationService
PaymentService -> AccountRepository
Step 6: Create AccountRepository (no dependencies)
Step 7: Create NotificationService (no dependencies)
Step 8: Create PaymentService (inject both)
Step 9: Call @PostConstruct on all beans
Step 10: Application ready
How is constructor injection different from field injection?
Spring supports three injection styles: constructor, setter, and field. Constructor injection is the recommended approach.
| Feature | Constructor Injection | Field Injection | Setter Injection |
|---|---|---|---|
| Annotation needed | None (single constructor) | @Autowired on field | @Autowired on setter |
| Immutability | Yes (final fields) | No | No |
| Required by default | Yes (fails at startup if missing) | No (null at runtime) | No |
| Testable without Spring | Yes (pass mocks in constructor) | No (need reflection or Spring) | Yes (call setter) |
| Circular dependency detection | Fails fast at startup | Silently allows | Silently allows |
| Recommended by Spring team | Yes | No | For optional dependencies |
package com.bank.core;
// Constructor injection (RECOMMENDED)
class PaymentServiceConstructor {
private final String notifierType;
private final String repoType;
// No @Autowired needed for a single constructor
PaymentServiceConstructor(String notifierType, String repoType) {
this.notifierType = notifierType;
this.repoType = repoType;
}
@Override
public String toString() {
return "PaymentService[notifier=" + notifierType + ", repo=" + repoType + "]";
}
}
// Field injection (NOT recommended)
class PaymentServiceField {
// @Autowired would go here in Spring
String notifierType;
String repoType;
@Override
public String toString() {
return "PaymentService[notifier=" + notifierType + ", repo=" + repoType + "]";
}
}
public class ConstructorVsFieldInjection {
public static void main(String[] args) {
// Constructor injection: dependencies are explicit and final
var constructorBased = new PaymentServiceConstructor("EmailNotifier", "JpaRepo");
System.out.println("Constructor injection: " + constructorBased);
// Field injection: dependencies can be null, not visible in constructor
var fieldBased = new PaymentServiceField();
fieldBased.notifierType = "EmailNotifier";
fieldBased.repoType = "JpaRepo";
System.out.println("Field injection: " + fieldBased);
// Testing advantage of constructor injection
var testService = new PaymentServiceConstructor("MockNotifier", "MockRepo");
System.out.println("Test with mocks: " + testService);
System.out.println();
System.out.println("Constructor injection wins because:");
System.out.println(" 1. Dependencies are final and immutable");
System.out.println(" 2. Cannot create the object without providing all dependencies");
System.out.println(" 3. Easy to test: just pass mocks in the constructor");
}
}
Expected output:
Constructor injection: PaymentService[notifier=EmailNotifier, repo=JpaRepo]
Field injection: PaymentService[notifier=EmailNotifier, repo=JpaRepo]
Test with mocks: PaymentService[notifier=MockNotifier, repo=MockRepo]
Constructor injection wins because:
1. Dependencies are final and immutable
2. Cannot create the object without providing all dependencies
3. Easy to test: just pass mocks in the constructor
What is a complete banking project using IoC?
This project shows a payment processing service where Spring manages all dependencies. The PaymentService depends on AccountRepository and NotificationService, and the container wires everything.
Project structure
bank-ioc-demo/
├── pom.xml
└── src/
├── main/
│ └── java/
│ └── com/
│ └── bank/
│ ├── BankIocDemoApplication.java
│ ├── model/
│ │ └── Account.java
│ ├── repository/
│ │ └── AccountRepository.java
│ ├── service/
│ │ ├── NotificationService.java
│ │ └── PaymentService.java
│ └── runner/
│ └── StartupRunner.java
└── test/
└── java/
└── com/
└── bank/
└── service/
└── PaymentServiceTest.java
pom.xml
<?xml version="1.0" encoding="UTF-8"?syn-kw">>
syn-kw"><project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0
http://maven.apache.org/xsd/maven-4.0.0.xsd"syn-kw">>
syn-kw"><modelVersionsyn-kw">>4.0.0syn-kw"></modelVersionsyn-kw">>
syn-kw"><parentsyn-kw">>
syn-kw"><groupIdsyn-kw">>org.springframework.bootsyn-kw"></groupIdsyn-kw">>
syn-kw"><artifactIdsyn-kw">>spring-boot-starter-parentsyn-kw"></artifactIdsyn-kw">>
syn-kw"><versionsyn-kw">>3.4.7syn-kw"></versionsyn-kw">>
syn-kw"></parentsyn-kw">>
syn-kw"><groupIdsyn-kw">>com.banksyn-kw"></groupIdsyn-kw">>
syn-kw"><artifactIdsyn-kw">>bank-ioc-demosyn-kw"></artifactIdsyn-kw">>
syn-kw"><versionsyn-kw">>1.0.0syn-kw"></versionsyn-kw">>
syn-kw"><propertiessyn-kw">>
syn-kw"><java.versionsyn-kw">>25syn-kw"></java.versionsyn-kw">>
syn-kw"></propertiessyn-kw">>
syn-kw"><dependenciessyn-kw">>
syn-kw"><dependencysyn-kw">>
syn-kw"><groupIdsyn-kw">>org.springframework.bootsyn-kw"></groupIdsyn-kw">>
syn-kw"><artifactIdsyn-kw">>spring-boot-startersyn-kw"></artifactIdsyn-kw">>
syn-kw"></dependencysyn-kw">>
syn-kw"><dependencysyn-kw">>
syn-kw"><groupIdsyn-kw">>org.springframework.bootsyn-kw"></groupIdsyn-kw">>
syn-kw"><artifactIdsyn-kw">>spring-boot-starter-testsyn-kw"></artifactIdsyn-kw">>
syn-kw"><scopesyn-kw">>testsyn-kw"></scopesyn-kw">>
syn-kw"></dependencysyn-kw">>
syn-kw"></dependenciessyn-kw">>
syn-kw"></projectsyn-kw">>
Account.java
package com.bank.model;
import java.math.BigDecimal;
public record Account(
String accountId,
String holderName,
BigDecimal balance
) {
public Account withBalance(BigDecimal newBalance) {
return new Account(accountId, holderName, newBalance);
}
}
AccountRepository.java
package com.bank.repository;
import com.bank.model.Account;
import jakarta.annotation.PostConstruct;
import org.springframework.stereotype.Repository;
import java.math.BigDecimal;
import java.util.Map;
import java.util.Optional;
import java.util.concurrent.ConcurrentHashMap;
@Repository
public class AccountRepository {
private final Map<String, Account> store = new ConcurrentHashMap<>();
@PostConstruct
void init() {
store.put("SAV2001", new Account("SAV2001", "Priya", new BigDecimal("150000.00")));
store.put("CUR3001", new Account("CUR3001", "Rajesh", new BigDecimal("500000.00")));
System.out.println("AccountRepository initialized with 2 accounts");
}
public Optional<Account> findById(String accountId) {
return Optional.ofNullable(store.get(accountId));
}
public void save(Account account) {
store.put(account.accountId(), account);
}
}
NotificationService.java
package com.bank.service;
import org.springframework.stereotype.Service;
import java.math.BigDecimal;
@Service
public class NotificationService {
public void notifyPayment(String accountId, BigDecimal amount) {
System.out.println("SMS sent to " + accountId + ": payment of " + amount + " INR processed");
}
}
PaymentService.java
package com.bank.service;
import com.bank.model.Account;
import com.bank.repository.AccountRepository;
import org.springframework.stereotype.Service;
import java.math.BigDecimal;
@Service
public class PaymentService {
private final AccountRepository accountRepository;
private final NotificationService notificationService;
// Constructor injection: Spring injects both dependencies
public PaymentService(AccountRepository accountRepository,
NotificationService notificationService) {
this.accountRepository = accountRepository;
this.notificationService = notificationService;
System.out.println("PaymentService created by Spring container");
}
public String processPayment(String fromAccountId, BigDecimal amount) {
Account account = accountRepository.findById(fromAccountId)
.orElseThrow(() -> new IllegalArgumentException("Account not found: " + fromAccountId));
if (account.balance().compareTo(amount) < 0) {
return "Insufficient balance in " + fromAccountId;
}
Account updated = account.withBalance(account.balance().subtract(amount));
accountRepository.save(updated);
notificationService.notifyPayment(fromAccountId, amount);
return "Payment of " + amount + " INR from " + fromAccountId + " successful. Balance: " + updated.balance();
}
}
StartupRunner.java
package com.bank.runner;
import com.bank.service.PaymentService;
import org.springframework.boot.CommandLineRunner;
import org.springframework.stereotype.Component;
import java.math.BigDecimal;
@Component
public class StartupRunner implements CommandLineRunner {
private final PaymentService paymentService;
public StartupRunner(PaymentService paymentService) {
this.paymentService = paymentService;
}
@Override
public void run(String... args) {
System.out.println();
System.out.println("--- Processing payments ---");
System.out.println(paymentService.processPayment("SAV2001", new BigDecimal("25000.00")));
System.out.println(paymentService.processPayment("CUR3001", new BigDecimal("100000.00")));
}
}
BankIocDemoApplication.java
package com.bank;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class BankIocDemoApplication {
public static void main(String[] args) {
SpringApplication.run(BankIocDemoApplication.class, args);
}
}
PaymentServiceTest.java
package com.bank.service;
import com.bank.model.Account;
import com.bank.repository.AccountRepository;
import org.junit.jupiter.api.Test;
import java.math.BigDecimal;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.mockito.Mockito.*;
class PaymentServiceTest {
@Test
void processPayment_deductsBalanceAndNotifies() {
// Because we used constructor injection, we can test without Spring
var accountRepo = mock(AccountRepository.class);
var notifier = mock(NotificationService.class);
var account = new Account("SAV2001", "Priya", new BigDecimal("150000.00"));
when(accountRepo.findById("SAV2001")).thenReturn(java.util.Optional.of(account));
var paymentService = new PaymentService(accountRepo, notifier);
String result = paymentService.processPayment("SAV2001", new BigDecimal("25000.00"));
assertTrue(result.contains("successful"));
verify(notifier).notifyPayment(eq("SAV2001"), eq(new BigDecimal("25000.00")));
System.out.println("Test passed: " + result);
}
}
Expected output (application run):
AccountRepository initialized with 2 accounts
PaymentService created by Spring container
--- Processing payments ---
SMS sent to SAV2001: payment of 25000.00 INR processed
Payment of 25000.00 INR from SAV2001 successful. Balance: 125000.00
SMS sent to CUR3001: payment of 100000.00 INR processed
Payment of 100000.00 INR from CUR3001 successful. Balance: 400000.00
How to run
cd bank-ioc-demo
mvn clean package -DskipTests
java -jar target/bank-ioc-demo-1.0.0.jar
# Run tests
mvn test
How does IoC look without Spring (manual wiring) vs with Spring?
The clearest way to understand IoC is to see the same application wired manually and then wired by Spring.
Without IoC: manual wiring
package com.bank.core;
import java.math.BigDecimal;
public class ManualWiringDemo {
public static void main(String[] args) {
// Developer controls everything: order of creation, wiring, lifecycle
var repo = new com.bank.repository.AccountRepository();
// Problem: @PostConstruct won't be called without Spring
var notifier = new com.bank.service.NotificationService();
var paymentService = new com.bank.service.PaymentService(repo, notifier);
System.out.println("Manual wiring: developer creates all 3 objects");
System.out.println("Manual wiring: developer decides the order");
System.out.println("Manual wiring: developer manages lifecycle");
System.out.println("Objects created: 3");
System.out.println();
System.out.println("Problems:");
System.out.println(" 1. If PaymentService adds a new dependency, caller must change");
System.out.println(" 2. No lifecycle management (@PostConstruct not called)");
System.out.println(" 3. No scope management (singleton vs prototype)");
System.out.println(" 4. Scales badly: 50 services = 50 manual wirings");
}
}
Expected output:
Manual wiring: developer creates all 3 objects
Manual wiring: developer decides the order
Manual wiring: developer manages lifecycle
Objects created: 3
Problems:
1. If PaymentService adds a new dependency, caller must change
2. No lifecycle management (@PostConstruct not called)
3. No scope management (singleton vs prototype)
4. Scales badly: 50 services = 50 manual wirings
With IoC: Spring handles everything
package com.bank.core;
public class SpringWiringDemo {
public static void main(String[] args) {
// In Spring, you write: @SpringBootApplication and declare @Service, @Repository
// The container does the rest.
System.out.println("Spring IoC wiring:");
System.out.println(" 1. Scans com.bank package");
System.out.println(" 2. Finds AccountRepository (@Repository)");
System.out.println(" 3. Finds NotificationService (@Service)");
System.out.println(" 4. Finds PaymentService (@Service)");
System.out.println(" 5. Sees PaymentService constructor needs both");
System.out.println(" 6. Creates AccountRepository first");
System.out.println(" 7. Calls @PostConstruct on AccountRepository");
System.out.println(" 8. Creates NotificationService");
System.out.println(" 9. Creates PaymentService, injects both");
System.out.println(" 10. Application ready");
System.out.println();
System.out.println("Developer wrote 0 lines of wiring code");
}
}
Expected output:
Spring IoC wiring:
1. Scans com.bank package
2. Finds AccountRepository (@Repository)
3. Finds NotificationService (@Service)
4. Finds PaymentService (@Service)
5. Sees PaymentService constructor needs both
6. Creates AccountRepository first
7. Calls @PostConstruct on AccountRepository
8. Creates NotificationService
9. Creates PaymentService, injects both
10. Application ready
Developer wrote 0 lines of wiring code
What are common mistakes when using IoC?
The most common mistake is using field injection with @Autowired instead of constructor injection.
Wrong: field injection
package com.bank.service;
import com.bank.repository.AccountRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
@Service
public class PaymentServiceWrong {
@Autowired
private AccountRepository accountRepository; // Not final, not explicit
@Autowired
private NotificationService notificationService; // Hidden dependency
public String processPayment(String accountId) {
return "Processing for " + accountId;
}
}
Problems with field injection:
1. Dependencies are hidden: you cannot see them from the constructor
2. Fields are not final: another thread could overwrite them
3. Cannot create PaymentServiceWrong without Spring (need reflection)
4. Unit tests require @SpringBootTest or reflection to set fields
5. Circular dependencies are silently allowed, causing runtime issues
Correct: constructor injection
package com.bank.service;
import com.bank.repository.AccountRepository;
import org.springframework.stereotype.Service;
@Service
public class PaymentServiceCorrect {
private final AccountRepository accountRepository;
private final NotificationService notificationService;
// Single constructor: no @Autowired needed
public PaymentServiceCorrect(AccountRepository accountRepository,
NotificationService notificationService) {
this.accountRepository = accountRepository;
this.notificationService = notificationService;
}
public String processPayment(String accountId) {
return "Processing for " + accountId;
}
}
Benefits of constructor injection:
1. Dependencies are explicit in the constructor signature
2. Fields are final: thread-safe, immutable
3. Can create the object with new in tests: new PaymentServiceCorrect(mockRepo, mockNotifier)
4. If you forget a dependency, the app fails at startup, not at runtime
5. Spring detects circular dependencies immediately
Wrong: creating beans manually inside Spring-managed code
package com.bank.service;
import org.springframework.stereotype.Service;
@Service
public class TransferServiceWrong {
public String transfer(String from, String to) {
// WRONG: creating a new instance bypasses the container
var notifier = new NotificationService();
notifier.notifyPayment(from, java.math.BigDecimal.ZERO);
return "Transferred from " + from + " to " + to;
}
}
Problem: new NotificationService() is not managed by Spring.
If NotificationService had its own dependencies, they would be null.
The container's singleton is ignored. AOP proxies (transactions, security) are bypassed.
Correct: let Spring inject the dependency
package com.bank.service;
import org.springframework.stereotype.Service;
import java.math.BigDecimal;
@Service
public class TransferServiceCorrect {
private final NotificationService notificationService;
public TransferServiceCorrect(NotificationService notificationService) {
this.notificationService = notificationService;
}
public String transfer(String from, String to) {
notificationService.notifyPayment(from, BigDecimal.ZERO);
return "Transferred from " + from + " to " + to;
}
}
Correct: NotificationService is injected by Spring.
It is the same singleton instance used everywhere.
AOP proxies work. Dependencies of NotificationService are also injected.
What about testing with IoC?
Constructor injection makes testing straightforward. You create the service with mock dependencies, without starting the Spring container.
package com.bank.service;
import com.bank.model.Account;
import com.bank.repository.AccountRepository;
import org.junit.jupiter.api.Test;
import java.math.BigDecimal;
import java.util.Optional;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.mockito.Mockito.*;
class PaymentServiceUnitTest {
private final AccountRepository accountRepo = mock(AccountRepository.class);
private final NotificationService notifier = mock(NotificationService.class);
private final PaymentService paymentService = new PaymentService(accountRepo, notifier);
@Test
void successfulPayment() {
var account = new Account("SAV2001", "Priya", new BigDecimal("100000.00"));
when(accountRepo.findById("SAV2001")).thenReturn(Optional.of(account));
String result = paymentService.processPayment("SAV2001", new BigDecimal("30000.00"));
assertTrue(result.contains("successful"));
verify(accountRepo).save(any(Account.class));
verify(notifier).notifyPayment("SAV2001", new BigDecimal("30000.00"));
System.out.println("Test 1 passed: " + result);
}
@Test
void insufficientBalance() {
var account = new Account("SAV2001", "Priya", new BigDecimal("1000.00"));
when(accountRepo.findById("SAV2001")).thenReturn(Optional.of(account));
String result = paymentService.processPayment("SAV2001", new BigDecimal("50000.00"));
assertEquals("Insufficient balance in SAV2001", result);
verify(notifier, never()).notifyPayment(any(), any());
System.out.println("Test 2 passed: " + result);
}
}
Expected output:
Test 1 passed: Payment of 30000.00 INR from SAV2001 successful. Balance: 70000.00
Test 2 passed: Insufficient balance in SAV2001
Key point: no @SpringBootTest, no application context, no slow startup.
Plain JUnit 5 + Mockito. Constructor injection made this possible.
What should a senior or principal engineer know?
At the senior level, you should understand IoC beyond the annotations. The container is not magic. It is a HashMap of bean names to bean instances, with a dependency graph that determines creation order.
- BeanFactory vs ApplicationContext: BeanFactory is the base interface with lazy bean creation. ApplicationContext extends it with eager initialization, event publishing, message resolution, and environment profiles. In production Spring Boot, you always use ApplicationContext.
- Bean scopes: singleton (one instance per container, default), prototype (new instance every time), request (one per HTTP request), session (one per HTTP session). Injecting a prototype into a singleton is a common bug: the prototype is created once and reused.
- Circular dependencies: if A depends on B and B depends on A through constructors, the container throws BeanCurrentlyInCreationException. Spring can resolve setter-based circulars with early references, but this is a design smell.
- BeanPostProcessor: the container calls BeanPostProcessor.postProcessBeforeInitialization and postProcessAfterInitialization around each bean. AOP proxies (@Transactional, @Cacheable) are created by a BeanPostProcessor.
- Startup performance: every @ComponentScan triggers classpath scanning. In large applications with hundreds of beans, startup can be slow. Spring AOT (Ahead of Time) in Spring Boot 3.x generates bean definitions at compile time to skip runtime scanning.
package com.bank.core;
public class SeniorIoCKnowledge {
public static void main(String[] args) {
System.out.println("Senior/Principal IoC Checklist:");
System.out.println(" 1. BeanFactory = lazy, ApplicationContext = eager + events + profiles");
System.out.println(" 2. Default scope is singleton: one instance per container");
System.out.println(" 3. Prototype in singleton = bug (injected once, reused forever)");
System.out.println(" 4. Circular constructor deps = BeanCurrentlyInCreationException");
System.out.println(" 5. @Transactional works via BeanPostProcessor creating a CGLIB proxy");
System.out.println(" 6. Spring AOT skips classpath scanning, generates bean defs at build time");
System.out.println(" 7. Use @Lazy on a dependency to break startup-time circular references");
System.out.println(" 8. Constructor injection + final fields = thread-safe immutable beans");
}
}
Expected output:
Senior/Principal IoC Checklist:
1. BeanFactory = lazy, ApplicationContext = eager + events + profiles
2. Default scope is singleton: one instance per container
3. Prototype in singleton = bug (injected once, reused forever)
4. Circular constructor deps = BeanCurrentlyInCreationException
5. @Transactional works via BeanPostProcessor creating a CGLIB proxy
6. Spring AOT skips classpath scanning, generates bean defs at build time
7. Use @Lazy on a dependency to break startup-time circular references
8. Constructor injection + final fields = thread-safe immutable beans
What are common interview follow-up questions?
- What is the difference between BeanFactory and ApplicationContext? (BeanFactory is lazy and minimal. ApplicationContext adds eager init, events, i18n, and profile support. Spring Boot always uses ApplicationContext.)
- Can you have two beans of the same type? (Yes. Use @Qualifier to tell Spring which one to inject. Without it, Spring throws NoUniqueBeanDefinitionException.)
- What happens if Spring cannot find a bean to inject? (The container throws NoSuchBeanDefinitionException at startup for constructor injection. For @Autowired(required = false), the field is null.)
- How does Spring handle circular dependencies? (Constructor-based circulars fail at startup. Setter-based circulars are resolved with early references, but the Spring team recommends redesigning instead.)
- What is the difference between @Autowired and constructor injection without @Autowired? (If a class has exactly one constructor, Spring uses it automatically. @Autowired is only needed when there are multiple constructors.)
- Can you use IoC without Spring Boot? (Yes. Use AnnotationConfigApplicationContext or ClassPathXmlApplicationContext from plain Spring Framework.)
Visual Overview
Without IoC (Traditional) ========================== ┌──────────────────────┐ │ main() method │ │ │ │ new AccountRepo() │──── Developer creates │ new NotifierService()│──── Developer creates │ new PaymentService( │──── Developer wires │ repo, notifier) │ │ │ │ paymentService.pay() │ └──────────────────────┘ Developer controls everything. 50 services = 50 manual wirings. With IoC (Spring Container) ============================ ┌─────────────────────────────────┐ │ Spring IoC Container │ │ (ApplicationContext) │ │ │ │ 1. Scan com.bank.* │ │ 2. Build dependency graph │ │ │ │ ┌──────────────┐ │ │ │ @Repository │ │ │ │ AccountRepo │────────┐ │ │ └──────────────┘ │ │ │ ▼ │ │ ┌──────────────┐ ┌─────────┐ │ │ │ @Service │ │ @Service│ │ │ │ Notifier │──▶│ Payment │ │ │ └──────────────┘ │ Service │ │ │ └─────────┘ │ │ │ │ 3. Inject dependencies │ │ 4. Call @PostConstruct │ │ 5. Application ready │ └─────────────────────────────────┘ Developer writes 0 lines of wiring code.
Key Takeaway
Inversion of Control is the foundation of everything Spring does. Instead of your code creating objects with the new keyword and wiring them together, the Spring container takes that responsibility. You declare what each class needs through its constructor, and the container builds the dependency graph, creates every object in the right order, and injects each dependency.
In our National Bank of India payment service, PaymentService needed AccountRepository and NotificationService. Without IoC, the main method would create all three objects manually, decide the order, and pass references. With Spring, we annotated each class with @Service or @Repository, wrote a single constructor, and the container handled everything. We wrote zero lines of wiring code.
The key benefit shows up in testing. Because PaymentService receives its dependencies through the constructor, we tested it with plain Mockito, no Spring context, no slow startup. We created mock objects and passed them directly. This is only possible with constructor injection, which is why the Spring team recommends it over field injection.
At the senior level, remember that the container is a HashMap of bean names to instances, backed by a dependency graph. BeanPostProcessors create AOP proxies for @Transactional and @Cacheable. The default scope is singleton, and injecting a prototype into a singleton is a common bug. Circular constructor dependencies fail fast at startup, which is the correct behavior.
Remember one sentence: IoC means the Spring container creates your objects and injects their dependencies, so your classes declare what they need instead of creating it themselves.
---