1. Why Spring? & What Is IoC?
IoC
Inversion Of Control — container manages objects
DI
Dependency Injection — container provides dependencies
Bean Management
Create, configure, destroy beans
AOP
Cross-cutting concerns handled separately
Spring Core is the foundation of the Spring Framework — provides IoC, Dependency Injection, Bean Management, the Container, and AOP support.
Without Spring vs With Spring
Without Spring
Developer Creates Objects
↓
Tight Coupling
↓
Difficult Testing & Maintenance
With Spring
Container Creates Objects
↓
Loose Coupling
↓
Easy Testing & Maintenance
IoC Definition & Flow
What Is IoC?
Inversion Of Control: the control of creating and managing objects is transferred from the developer to the Spring Container.
Without IoC vs With IoC
Without: Application → Developer creates objects using `new` → Tight Coupling
With: Application → Spring Container → Creates Beans → Injects Dependencies → Loose Coupling
IoC Flow
Application Starts
↓
Spring Reads Configuration
↓
Creates Beans → Resolves Dependencies
↓
Injects Beans → Application Ready
Benefits of IoC: Loose Coupling, Better Testing, Easier Maintenance, Reusable Components, Centralized Object Management, Better Scalability.
2. IoC Container — BeanFactory vs ApplicationContext
IoC Container Responsibilities
Core component responsible for: Creating, Managing, Configuring, Destroying Beans
Also handles: Injecting Dependencies, Managing Lifecycle, Handling Bean Scope, Publishing Events
Container Hierarchy
IoC Container
├── BeanFactory — Basic Container
└── ApplicationContext — Advanced Container, extends BeanFactory
TypeBasic Container
LoadingLazy Initialization — creates bean only when requested
FootprintLightweight, Less Features, Legacy
TypeAdvanced Container (Preferred)
LoadingCreates Singleton Beans at Startup (Eager by default)
ExtrasEvents, Internationalization, AOP Support, Resource Loading, Environment Support
Why ApplicationContext? Better performance for enterprise apps, Event Publishing, Validation, AOP, Message Resources, Environment Profiles.
3. Spring Bean & Dependency Injection
Spring Bean
An object created, managed and destroyed by the Spring Container.
Examples: UserService, UserRepository, EmailService, PaymentService
Without DI vs With DI
Without: UserService → new UserRepository() → Tight Coupling
With: Spring Container → Creates Repository → Injects Into Service → Loose Coupling
Dependency Injection Flow
Container Starts
→
Create Repository Bean
→
Create Service Bean
→
Inject Repository
→
Ready To Use
Types of Dependency Injection
Constructor Injection ⭐
Dependency passed through the constructor.
ImmutableMandatory DependencyEasy Unit TestingRecommended
Setter Injection
Dependency injected using a setter method.
Optional DependencyCan Be Changed Later
Field Injection
Dependency injected directly into the field using @Autowired.
Simple But Not Recommended For Production
| Type | Nature | Testability | Verdict |
| Constructor | Mandatory, Immutable | Easy | Best Choice |
| Setter | Optional, Mutable | Moderate | Use When Needed |
| Field | Simple | Hard To Test | Avoid |
4. @Autowired, Autowiring Resolution & Circular Dependency
@Autowired
Purpose: automatically inject a bean by type.
Works on: Constructor, Setter, Field.
Autowiring Modes
By Type (Default)
By Name using @Qualifier
Primary Bean using @Primary
Autowiring Resolution Order
@Autowired → By Type
↓ Multiple Beans?
@Qualifier
↓ Still Multiple?
@Primary
↓ Still Ambiguous?
NoUniqueBeanDefinitionException
Circular Dependency
Circular Dependency Flow
Bean A → Needs Bean B
↓
Bean B → Needs Bean A
↓
Cycle → Application Startup Fails
How To Resolve Circular Dependency?
✓ Redesign Classes
✓ Introduce Third Service
✓ Use @Lazy (If Necessary)
✓ Prefer Constructor Injection
✓ Avoid Circular Design
5. Spring Bean Lifecycle
Complete Bean Lifecycle
Application Starts → Container Starts
↓
Instantiate Bean → Dependency Injection
↓
@PostConstruct → InitializingBean.afterPropertiesSet() → Custom Init Method
↓
Bean Ready → Application Uses Bean
↓
@PreDestroy → DisposableBean.destroy() → Custom Destroy Method → Bean Destroyed
Lifecycle Phases
1. Instantiation
2. Dependency Injection
3. Initialization
4. Ready To Use
5. Destruction
Init & Destroy Hooks
RunsImmediately after Dependency Injection, before use
UsesLoad Cache, Initialize Resources, Validate Config, Start Scheduler
RunsBefore bean destruction
UsesClose Connections, Stop Threads, Flush Cache, Release Resources
| Annotation-Based | Interface-Based (Legacy) |
| @PostConstruct | InitializingBean.afterPropertiesSet() |
| @PreDestroy | DisposableBean.destroy() |
Custom init/destroy methods: declared via @Bean(initMethod=..., destroyMethod=...) — useful for third-party classes you cannot modify.
@PostConstruct vs Constructor: in the constructor, dependencies may not exist yet; @PostConstruct runs after DI, when all beans are ready — preferred for initialization logic.
6. Bean Scopes
Singleton
Default scope. One bean per Spring container, shared instance.
Memory Efficient
Prototype
New bean created every request. Independent object, no automatic destroy.
More Memory
Request
One bean per HTTP request, destroyed after the request completes.
Session
One bean per user session, destroyed when session ends.
Application
One bean per ServletContext, shared across the entire web app.
Singleton Flow
Application
→
Container
→
Creates One Bean
→
All Consumers Share Same Instance
Prototype Flow
Request 1 → Bean A
Request 2 → Bean B
Different objects each time — a new bean per request.
Singleton characteristics: Shared Instance, Memory Efficient, Thread Safety Required. Session scope example: Shopping Cart, Logged-in User Data.
7. Stereotype Annotations
@Component
Generic Spring-managed bean, used when no specific layer applies.
@Service
Represents Business Logic / Service Layer. Specialization of @Component.
@Repository
Represents Persistence Layer / Database Access. Adds Exception Translation.
@Controller
Spring MVC Controller. Returns a View Name (JSP/Thymeleaf).
@RestController
@Controller + @ResponseBody. Returns JSON/XML — preferred for REST APIs.
8. Java Config — @Bean, @Configuration, @ComponentScan
| Annotation | Purpose |
| @Bean | Registers a bean using Java configuration; used inside @Configuration classes; common for third-party libraries, custom config, external SDKs |
| @Configuration | Marks a configuration class containing @Bean methods — equivalent to XML configuration |
| @ComponentScan | Scans packages for @Component/@Service/@Repository/@Controller/@RestController and automatically registers beans |
| @ConfigurationProperties | Binds application.properties/application.yml to a Java object — type safe, clean configuration |
| @ConfigurationPropertiesScan | Automatically scans @ConfigurationProperties classes — no need for @Component on the config class |
OwnershipClass owned by developer
RegistrationAuto scanned
OwnershipExternal / third-party class
RegistrationManual registration, inside @Configuration
9. @Primary, @Qualifier & @Lazy
PurposeMarks the default bean when multiple beans of the same type exist
ScopeGlobal preference
Use WhenDefault implementation, reduce ambiguity
PurposeSelects a specific bean among multiple beans of the same type
ScopeInjection point preference
ExampleNotificationService needs EmailService instead of SmsService
Eager vs Lazy Initialization
Eager (Default Singleton): Application Starts → Bean Created
Lazy (@Lazy): Application Starts → Bean Not Created → First Request → Bean Created
When to use @Lazy? Heavy beans, expensive initialization, rarely-used services, or as a temporary fix for circular dependencies.
Example — @Primary vs @Qualifier
PaymentService
├── UPI
└── CreditCard @Primary
Spring injects CreditCard unless @Qualifier is explicitly used to pick UPI.
10. Spring Events
Event Flow
Publisher
→
ApplicationEventPublisher
→
Spring Event Bus
→
@EventListener
→
Listener Executes
Why use events? Loose Coupling, Better Maintainability, Asynchronous Processing, Event-Driven Architecture.
Real Event Example
User Registers → UserRegisteredEvent
├── Email Service → Send Welcome Email
├── Audit Service → Store Audit Log
└── Notification Service → Send SMS
Built-in Spring Events
| ContextRefreshedEvent | Application Started |
| ContextClosedEvent | Application Shutdown |
| ContextStartedEvent | Context Started |
| ContextStoppedEvent | Context Stopped |
| ApplicationReadyEvent | Spring Boot Ready |
11. AOP — Aspect Oriented Programming
Without AOP vs With AOP
Without: Logging, Security, Transactions repeated in every method
With: Business Logic → Aspect handles Logging, Security, Auditing, Transactions
Cross-cutting concerns: Logging, Security, Auditing, Transactions, Caching, Monitoring, Validation, Performance Measurement.
AOP Terminology
| Aspect | Module containing cross-cutting logic |
| Advice | Action to execute |
| Join Point | A point of method execution |
| Pointcut | Expression that selects join points |
| Weaving | Applying the aspect to target code |
| Proxy | Object created by Spring to apply advice |
Types of Advice
@Before
Runs before the method executes.
@After
Runs after the method (regardless of outcome).
@AfterReturning
Runs only on successful return.
@AfterThrowing
Runs only when an exception is thrown.
@Around ⭐
Wraps before + after — most powerful advice type.
AOP Execution Flow
Client → Proxy
↓
@Before → Business Method
↓
@AfterReturning → Return Response
↓ If Exception
@AfterThrowing
Transaction Proxy
Client → Proxy → Begin Transaction
↓
Business Logic
↓ Success? → Commit / Failure? →
Rollback
Spring AOP use cases: Logging (request/response), Security (role checks), Transactions (commit/rollback), Performance (execution time), Auditing (store audit logs). Proxy: Spring creates a proxy object instead of the original bean, adding logging/security/transactions without changing business code.
12. Enterprise Best Practices & Common Interview Questions
Enterprise Best Practices (All Parts Combined)
✓Prefer ApplicationContext over BeanFactory
✓Use Constructor Injection everywhere possible
✓Keep dependencies immutable; avoid Field Injection
✓Design for loose coupling; program to interfaces
✓Keep services focused; avoid circular dependencies
✓Keep services Singleton; avoid stateful singleton beans
✓Use Prototype scope only when necessary
✓Prefer @PostConstruct over constructor init logic
✓Use @Bean for third-party objects (RestTemplate, ObjectMapper, S3 Client)
✓Use @ConfigurationProperties for config values
✓Use @Qualifier for explicit bean selection
✓Use @Primary for default implementations
✓Avoid excessive @Lazy usage
✓Publish business events instead of tight coupling
✓Keep event listeners independent
✓Use AOP for logging, security, auditing — not business logic
✓Keep pointcuts specific; use @Around only when necessary
✓Let @Transactional handle transaction boundaries
Common Interview Questions
What is IoC?
Spring controls object creation instead of the developer doing it manually with `new`.
Why Dependency Injection?
Achieves loose coupling — objects don't create their own dependencies, making code easier to test and maintain.
BeanFactory or ApplicationContext?
ApplicationContext — it's the advanced, preferred container with more enterprise features.
Why Constructor Injection over Field Injection?
Constructor Injection gives immutability, mandatory dependency enforcement, and easy unit testing. Field Injection hides dependencies and is hard to unit test.
Does Spring destroy Prototype beans automatically?
No — the developer is responsible for cleanup of prototype-scoped beans.
Why is Singleton the default scope?
Memory efficiency and better performance — one shared instance instead of creating a new object per request.
Difference between @Component and @Bean?
@Component is auto-scanned on classes you own; @Bean is manually registered inside a @Configuration class, typically for third-party/external classes.
Why use @Repository specifically?
It adds exception translation — converting database-specific exceptions into Spring's consistent DataAccessException hierarchy.
What is the most powerful AOP advice type?
@Around — because it wraps both before and after logic around the method execution, and can even control whether the method runs at all.
13. Interview One-Liner Revision
›Spring Core → Foundation Of Spring
›IoC → Inversion Of Control
›IoC Container → Manages Beans
›Bean → Spring Managed Object
›BeanFactory → Basic Container
›ApplicationContext → Advanced Container
›DI → Dependency Injection
›Constructor Injection → Best Practice
›Setter Injection → Optional Dependency
›Field Injection → Avoid In Production
›@Autowired → Automatic Bean Injection
›Circular Dependency → Beans Depend On Each Other
›Bean Lifecycle → Create To Destroy
›@PostConstruct → After Dependency Injection
›@PreDestroy → Before Bean Destroy
›Singleton → One Bean (Default)
›Prototype → New Bean Each Time
›Request Scope → Per HTTP Request
›Session Scope → Per User Session
›Application Scope → Per Web Application
›@Component → Generic Bean
›@Service → Business Layer
›@Repository → Persistence Layer
›@Controller → MVC Controller
›@RestController → REST Controller
›@Bean → Manual Bean Registration
›@Configuration → Java Configuration
›@ComponentScan → Auto Bean Discovery
›@ConfigurationProperties → Bind External Configuration
›@Primary → Default Bean
›@Qualifier → Specific Bean
›@Lazy → Lazy Initialization
›ApplicationEventPublisher → Publish Event
›@EventListener → Listen Event
›Spring Event → Communication Between Components
›AOP → Cross-Cutting Concern
›Aspect → Module
›Advice → Action
›Join Point → Method Execution
›Pointcut → Select Join Point
›Proxy → Spring Wrapper
›@Before → Before Execution
›@After → After Execution
›@Around → Before And After
›Transaction Proxy → Commit/Rollback
14. Real Project Scenarios
UserService→Inject UserRepository
OrderService→Inject PaymentService, InventoryService
NotificationService→Inject EmailService, SmsService
@PostConstruct→Load Country Cache
@PreDestroy→Close Kafka Producer
Singleton→UserService, PaymentService
Prototype→PDF Generator, Report Builder
@SessionScope→Shopping Cart, Logged-in User
@Bean→AWS S3 Client, Mail Sender, ObjectMapper, RestTemplate, WebClient
@Qualifier→Choose StripePaymentService over PaypalPaymentService
@Lazy→Large ML Model, PDF Generator, Report Engine
Spring Events→User Registered → Send Email → Audit → Notification
AOP→Log Every API Request, Measure Response Time, Security Check, Audit Changes
Transactions→Bank Transfer → Commit → Rollback On Failure
CertifyHub→UserController → UserService → UserRepository
15. 15-Minute Spring Core Revision Flow
Spring Core → IoC → ApplicationContext
↓
Dependency Injection (Constructor/Setter/Field)
↓
Bean Lifecycle → Scopes
↓
@Component → @Service → @Repository
↓
@Bean → @Configuration
↓
@Primary → @Qualifier → @Lazy
↓
Events → AOP → Best Practices
Interviewers Expect You To Explain
✓ IoC & DI in your own words with real examples ✓ Why Constructor Injection is preferred
✓ Full Bean Lifecycle including hooks ✓ When to use each Bean Scope
✓ Autowiring resolution order & ambiguity handling ✓ AOP terminology and a real use case (logging/transactions)
✓ How you've used Spring Events or AOP in a real project