Definition
- ApplicationContext is the central interface for the Spring IoC container. It reads configuration metadata, instantiates beans, injects dependencies, and manages their lifecycle.
- Component scanning is the automatic process where Spring scans specified packages for classes annotated with stereotype annotations and registers them as bean definitions.
- Stereotype annotations such as @Component, @Service, @Repository, and @Controller mark classes for automatic detection during scanning.
- Auto-configuration in Spring Boot registers additional beans based on classpath dependencies, removing the need for manual configuration.
- Bean lifecycle covers the complete journey from instantiation through dependency injection, initialization callbacks, active use, and destruction callbacks.
Think of a bank branch. The branch manager (ApplicationContext) does not personally perform every task. The manager hires staff (beans), assigns them to departments (packages), and makes sure each employee has the tools and colleagues they need (dependency injection). Component scanning is like the HR department reading resumes (class annotations) and automatically placing new hires in the right department. The branch manager knows every employee, their role, and when they start or leave.
Understanding the Concepts
What is ApplicationContext?
ApplicationContext is the central interface for the Spring IoC (Inversion of Control) container. It reads your configuration metadata, whether that is annotations, Java configuration classes, or XML files. Then it creates bean instances, injects their dependencies, publishes application events, and manages the complete lifecycle of every bean.
In a Spring Boot application, SpringApplication.run() creates and returns an ApplicationContext. You can use it to inspect registered beans, retrieve beans by name or type, and access environment properties.
package com.bank;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.ApplicationContext;
import java.util.Arrays;
@SpringBootApplication
public class BankApplication {
public static void main(String[] args) {
ApplicationContext context = SpringApplication.run(
BankApplication.class, args);
System.out.println("Total beans: " + context.getBeanDefinitionCount());
// Filter for our banking beans
String[] bankBeans = Arrays.stream(context.getBeanDefinitionNames())
.filter(n -> n.startsWith("account") || n.startsWith("transaction"))
.toArray(String[]::new);
for (String name : bankBeans) {
Object bean = context.getBean(name);
System.out.println("Bean: " + name
+ " -> " + bean.getClass().getSimpleName());
}
}
}
Total beans: 148
Bean: accountController -> AccountController
Bean: accountService -> AccountService
Bean: accountRepository -> AccountRepository
Bean: transactionService -> TransactionService
The container registers your application beans along with infrastructure beans from Spring Boot auto-configuration. The number 148 includes both your custom beans and framework beans like dataSource, transactionManager, and objectMapper.
What is Inversion of Control (IoC)?
Inversion of Control means the framework creates and manages objects instead of your code doing it manually. Without IoC, every class creates its own dependencies using new. With IoC, you declare what you need, and the container provides it.
This is the fundamental principle behind ApplicationContext. You never call new AccountService() yourself. Instead, Spring creates the service, creates everything it depends on, and wires them together.
Without IoC (manual creation)
package com.bank.service;
import com.bank.repository.AccountRepository;
import java.math.BigDecimal;
// Problem: AccountService creates its own dependency.
// You cannot swap the repository for testing.
public class AccountService {
// Tightly coupled. Hard to test, hard to change.
private final AccountRepository repository = new AccountRepository();
public BigDecimal getBalance(String accountId) {
return repository.findBalance(accountId);
}
}
With IoC (container-managed)
package com.bank.service;
import com.bank.repository.AccountRepository;
import org.springframework.stereotype.Service;
import java.math.BigDecimal;
@Service
public class AccountService {
// Spring injects the repository. Easy to test with a mock.
private final AccountRepository repository;
public AccountService(AccountRepository repository) {
this.repository = repository;
}
public BigDecimal getBalance(String accountId) {
return repository.findBalance(accountId);
}
}
// In a test, you can inject a mock:
AccountRepository mock = Mockito.mock(AccountRepository.class);
when(mock.findBalance("SAV2001")).thenReturn(new BigDecimal("50000.00"));
AccountService service = new AccountService(mock);
assertEquals(new BigDecimal("50000.00"), service.getBalance("SAV2001"));
The IoC version is loosely coupled. You can swap the repository for a mock in tests, a different database in staging, or a cache-backed version in production, all without changing AccountService.
How does component scanning discover beans?
When Spring Boot starts, it performs these steps:
- It finds the class annotated with
@SpringBootApplication. - It reads the package of that class (for example,
com.bank). - It scans
com.bankand every sub-package (com.bank.service,com.bank.repository,com.bank.controller). - For every class it finds with a stereotype annotation, it creates a
BeanDefinitionand registers it with the ApplicationContext. - After all definitions are registered, the container instantiates beans and injects dependencies.
@SpringBootApplication is a composite annotation that includes @ComponentScan. By default, it scans from the annotated class's package downward.
package com.bank;
// This lives in com.bank. Spring scans:
// com.bank.*
// com.bank.service.*
// com.bank.repository.*
// com.bank.controller.*
// com.bank.config.*
@SpringBootApplication
public class BankApplication {
public static void main(String[] args) {
SpringApplication.run(BankApplication.class, args);
}
}
package com.bank.service;
import org.springframework.stereotype.Service;
import java.math.BigDecimal;
@Service // Discovered by component scanning
public class TransactionService {
public BigDecimal calculateInterest(BigDecimal principal, BigDecimal rate) {
return principal.multiply(rate).setScale(2, java.math.RoundingMode.HALF_UP);
}
}
package com.bank.repository;
import org.springframework.stereotype.Repository;
import java.math.BigDecimal;
import java.util.Map;
@Repository // Discovered by component scanning
public class AccountRepository {
private final Map<String, BigDecimal> accounts = Map.of(
"SAV2001", new BigDecimal("75000.00"),
"SAV2002", new BigDecimal("120000.00")
);
public BigDecimal findBalance(String accountId) {
return accounts.getOrDefault(accountId, BigDecimal.ZERO);
}
}
// During startup, Spring logs:
Creating shared instance of singleton bean 'transactionService'
Creating shared instance of singleton bean 'accountRepository'
Creating shared instance of singleton bean 'accountService'
What stereotype annotations register beans?
Spring provides four stereotype annotations. Each one is a specialization of @Component.
| Annotation | Layer | Purpose |
|---|---|---|
@Component | Generic | Marks any class as a Spring-managed bean. |
@Service | Business | Marks a class that contains business logic. No extra behavior beyond @Component. |
@Repository | Data access | Marks a DAO class. Spring adds automatic exception translation for database errors. |
@Controller | Web | Marks an MVC controller. Combined with @RequestMapping to handle HTTP requests. |
@RestController | Web | Combines @Controller and @ResponseBody. Every method returns data directly, not a view name. |
@Configuration | Config | Marks a class that defines @Bean methods. Spring ensures CGLIB proxying for singleton scope. |
Using the right annotation communicates intent and enables layer-specific features.
package com.bank.controller;
import com.bank.service.AccountService;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import java.math.BigDecimal;
@RestController
@RequestMapping("/api/accounts")
public class AccountController {
private final AccountService accountService;
public AccountController(AccountService accountService) {
this.accountService = accountService;
}
@GetMapping("/{accountId}/balance")
public BigDecimal getBalance(@PathVariable String accountId) {
return accountService.getBalance(accountId);
}
}
GET /api/accounts/SAV2001/balance
Response: 75000.00
How is ApplicationContext different from BeanFactory?
BeanFactory is the base interface for the IoC container. ApplicationContext extends BeanFactory and adds enterprise features.
| Feature | BeanFactory | ApplicationContext |
|---|---|---|
| Bean creation and DI | Yes | Yes |
| Lazy initialization by default | Yes | No (eager by default) |
| Event publishing | No | Yes (ApplicationEvent) |
| Internationalization (i18n) | No | Yes (MessageSource) |
| Environment abstraction | No | Yes (profiles, properties) |
| AOP integration | Limited | Full |
| Web-aware contexts | No | Yes (WebApplicationContext) |
| BeanPostProcessor auto-registration | Manual | Automatic |
BeanFactory creates beans lazily: only when you call getBean(). ApplicationContext creates all singleton beans eagerly at startup, which catches configuration errors early.
package com.bank.config;
import com.bank.service.AccountService;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.xml.XmlBeanFactory;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.core.io.ClassPathResource;
public class ContainerComparison {
public static void main(String[] args) {
// ApplicationContext: creates all singletons eagerly at startup.
// Catches wiring errors immediately.
ApplicationContext appContext =
new AnnotationConfigApplicationContext("com.bank");
AccountService service = appContext.getBean(AccountService.class);
System.out.println("AccountService loaded: " + (service != null));
System.out.println("Environment: "
+ appContext.getEnvironment().getActiveProfiles().length
+ " active profiles");
// BeanFactory: creates beans only when requested.
// Errors surface later at runtime, not at startup.
// In modern Spring, you almost never use BeanFactory directly.
}
}
AccountService loaded: true
Environment: 0 active profiles
In practice, always use ApplicationContext. BeanFactory exists as the foundation interface, but direct use is rare in modern Spring Boot applications.
What is the complete bean lifecycle?
Every Spring bean goes through a well-defined lifecycle from creation to destruction.
- Instantiation: Spring calls the constructor (or factory method) to create the object.
- Dependency injection: Spring injects values via constructor, setter, or field injection.
- Aware interfaces: Spring calls
setBeanName(),setBeanFactory(),setApplicationContext()if the bean implements the corresponding Aware interfaces. - BeanPostProcessor.postProcessBeforeInitialization: All registered BeanPostProcessors run their "before" method.
- @PostConstruct: The method annotated with @PostConstruct runs.
- InitializingBean.afterPropertiesSet(): If the bean implements InitializingBean, this method runs.
- Custom init method: If specified via
@Bean(initMethod = "..."), the custom init method runs. - BeanPostProcessor.postProcessAfterInitialization: All registered BeanPostProcessors run their "after" method. This is where Spring creates proxies for AOP, @Transactional, and @Cacheable.
- Bean is ready: The bean is fully initialized and available for use.
- @PreDestroy: When the context shuts down, the @PreDestroy method runs.
- DisposableBean.destroy(): If the bean implements DisposableBean, this method runs.
- Custom destroy method: If specified, the custom destroy method runs.
package com.bank.service;
import jakarta.annotation.PostConstruct;
import jakarta.annotation.PreDestroy;
import org.springframework.stereotype.Service;
import java.math.BigDecimal;
import java.util.logging.Logger;
@Service
public class AccountService {
private static final Logger log =
Logger.getLogger(AccountService.class.getName());
private final AccountRepository repository;
private BigDecimal dailyTransferLimit;
public AccountService(AccountRepository repository) {
log.info("1. Constructor called: injecting AccountRepository");
this.repository = repository;
}
@PostConstruct
public void init() {
log.info("2. @PostConstruct: loading configuration");
this.dailyTransferLimit = new BigDecimal("500000.00");
log.info(" Daily transfer limit set to: " + dailyTransferLimit);
}
public BigDecimal getBalance(String accountId) {
return repository.findBalance(accountId);
}
@PreDestroy
public void cleanup() {
log.info("3. @PreDestroy: releasing resources");
}
}
1. Constructor called: injecting AccountRepository
2. @PostConstruct: loading configuration
Daily transfer limit set to: 500000.00
... application runs ...
3. @PreDestroy: releasing resources
How do you customize component scanning?
The default scan from the @SpringBootApplication package is enough for most projects. When you need beans from other packages or want to exclude certain classes, use @ComponentScan.
package com.bank;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.FilterType;
@SpringBootApplication
@ComponentScan(
basePackages = {
"com.bank",
"com.bank.shared.audit" // external shared library
},
excludeFilters = @ComponentScan.Filter(
type = FilterType.REGEX,
pattern = "com\\.bank\\.legacy\\..*"
)
)
public class BankApplication {
public static void main(String[] args) {
SpringApplication.run(BankApplication.class, args);
}
}
// Scans:
// com.bank.service.AccountService -> registered
// com.bank.shared.audit.AuditService -> registered
// com.bank.legacy.OldTransferService -> excluded by regex filter
You can also use FilterType.ANNOTATION, FilterType.ASSIGNABLE_TYPE, or FilterType.CUSTOM to build precise inclusion and exclusion rules.
What about bean scopes?
Spring supports several bean scopes. The two most common are singleton and prototype.
| Scope | Instances | Created When | Destroyed When |
|---|---|---|---|
singleton (default) | One per ApplicationContext | Context startup | Context shutdown |
prototype | New instance per request | Each getBean() call | Never (you manage it) |
request | One per HTTP request | Request starts | Request ends |
session | One per HTTP session | Session created | Session expires |
application | One per ServletContext | App starts | App stops |
package com.bank.service;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;
import java.math.BigDecimal;
import java.time.LocalDateTime;
@Component
@Scope("prototype")
public class TransferRequest {
private final LocalDateTime createdAt = LocalDateTime.now();
private String fromAccount;
private String toAccount;
private BigDecimal amount;
public LocalDateTime getCreatedAt() {
return createdAt;
}
// setters and getters omitted for brevity
}
package com.bank;
import com.bank.service.TransferRequest;
import org.springframework.boot.CommandLineRunner;
import org.springframework.context.ApplicationContext;
import org.springframework.stereotype.Component;
@Component
public class ScopeDemo implements CommandLineRunner {
private final ApplicationContext context;
public ScopeDemo(ApplicationContext context) {
this.context = context;
}
@Override
public void run(String... args) {
TransferRequest r1 = context.getBean(TransferRequest.class);
TransferRequest r2 = context.getBean(TransferRequest.class);
System.out.println("Same instance? " + (r1 == r2));
System.out.println("r1 created: " + r1.getCreatedAt());
System.out.println("r2 created: " + r2.getCreatedAt());
}
}
Same instance? false
r1 created: 2025-01-15T09:30:00.123
r2 created: 2025-01-15T09:30:00.125
Prototype beans get a fresh instance on every request. Spring does not manage their destruction, so you are responsible for closing any resources they hold.
What are common mistakes with component scanning?
Mistake 1: Main class in the wrong package
WRONG: Placing @SpringBootApplication in a package that does not contain your beans.
// WRONG: Main class is in com.bank.app
// but services are in com.bank.service
package com.bank.app;
@SpringBootApplication
public class BankApplication {
public static void main(String[] args) {
SpringApplication.run(BankApplication.class, args);
}
}
// com.bank.service.AccountService will NOT be scanned
// because com.bank.service is not a sub-package of com.bank.app
***************************
APPLICATION FAILED TO START
***************************
Parameter 0 of constructor in com.bank.controller.AccountController
required a bean of type 'com.bank.service.AccountService'
that could not be found.
CORRECT: Place the main class in the root package.
// CORRECT: Main class is in com.bank
// All sub-packages are scanned automatically
package com.bank;
@SpringBootApplication
public class BankApplication {
public static void main(String[] args) {
SpringApplication.run(BankApplication.class, args);
}
}
Mistake 2: Missing annotation on a bean class
WRONG: Forgetting the stereotype annotation.
package com.bank.service;
// WRONG: No @Service or @Component annotation
public class LoanCalculator {
public java.math.BigDecimal calculateEMI(
java.math.BigDecimal principal,
java.math.BigDecimal rate,
int months) {
// EMI calculation
return principal.divide(
java.math.BigDecimal.valueOf(months),
2, java.math.RoundingMode.HALF_UP);
}
}
CORRECT: Add the stereotype annotation.
package com.bank.service;
import org.springframework.stereotype.Service;
import java.math.BigDecimal;
import java.math.RoundingMode;
@Service // Now Spring discovers and registers this bean
public class LoanCalculator {
public BigDecimal calculateEMI(
BigDecimal principal, BigDecimal rate, int months) {
return principal.divide(
BigDecimal.valueOf(months), 2, RoundingMode.HALF_UP);
}
}
What about conditional beans and profiles?
Spring supports registering beans conditionally based on the active profile, a property value, or a class on the classpath.
Profile-based beans
package com.bank.config;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Profile;
import javax.sql.DataSource;
import org.springframework.boot.jdbc.DataSourceBuilder;
@Configuration
public class DataSourceConfig {
@Bean
@Profile("dev")
public DataSource devDataSource() {
return DataSourceBuilder.create()
.url("jdbc:h2:mem:bankdb")
.username("sa")
.password("")
.build();
}
@Bean
@Profile("prod")
public DataSource prodDataSource() {
return DataSourceBuilder.create()
.url("jdbc:postgresql://db.nationalbank.in:5432/bankdb")
.username("bank_app")
.password("${DB_PASSWORD}")
.build();
}
}
# application-dev.properties
spring.profiles.active=dev
# Startup log:
The following 1 profile is active: "dev"
DevDataSource created: jdbc:h2:mem:bankdb
Conditional on property
package com.bank.config;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@Configuration
public class NotificationConfig {
@Bean
@ConditionalOnProperty(
name = "bank.notifications.sms.enabled",
havingValue = "true"
)
public SmsNotificationService smsNotificationService() {
return new SmsNotificationService();
}
}
# application.properties
bank.notifications.sms.enabled=true
# Startup log:
Creating shared instance of singleton bean 'smsNotificationService'
What should a senior or principal engineer know?
- BeanFactoryPostProcessor vs BeanPostProcessor. A BeanFactoryPostProcessor modifies bean definitions before any beans are created. A BeanPostProcessor modifies bean instances after they are created. PropertySourcesPlaceholderConfigurer is a common BeanFactoryPostProcessor that resolves ${...} placeholders. AutowiredAnnotationBeanPostProcessor is a BeanPostProcessor that processes @Autowired.
- Classpath scanning performance. In large monoliths with thousands of classes, component scanning can add seconds to startup time. Mitigate this by narrowing basePackages or using Spring's Ahead-of-Time (AOT) processing in Spring Boot 3.x, which moves bean registration to compile time.
- ApplicationContext hierarchy. In a traditional Spring MVC application (not Spring Boot), there can be a parent context (root) and child contexts (per DispatcherServlet). Beans in the child context can access beans in the parent, but not the other way around. Spring Boot applications use a flat context by default.
- Spring Boot auto-configuration order. Auto-configuration classes are registered via META-INF/spring/org.springframework.boot.autoconfigure.AutoConfiguration.imports. They run after your @Configuration classes, so your beans take precedence. Use @AutoConfigureBefore, @AutoConfigureAfter, and @AutoConfigureOrder to control ordering.
- Virtual threads in Spring Boot 3.4. Setting spring.threads.virtual.enabled=true makes the embedded Tomcat server use virtual threads for request handling. Each request gets its own virtual thread, which is cheap to create and block. This works seamlessly with Spring's synchronous programming model.
- GraalVM native image. Spring Boot 3.x supports compiling to native executables. Component scanning is replaced by AOT-generated code that registers beans without runtime reflection. This eliminates classpath scanning entirely and reduces startup to milliseconds.
package com.bank.config;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.BeanPostProcessor;
import org.springframework.stereotype.Component;
import java.util.logging.Logger;
@Component
public class BankBeanAuditor implements BeanPostProcessor {
private static final Logger log =
Logger.getLogger(BankBeanAuditor.class.getName());
@Override
public Object postProcessAfterInitialization(
Object bean, String beanName) throws BeansException {
if (bean.getClass().getPackageName().startsWith("com.bank")) {
log.info("Audited bean: " + beanName
+ " [" + bean.getClass().getSimpleName() + "]");
}
return bean;
}
}
Audited bean: accountRepository [AccountRepository]
Audited bean: accountService [AccountService]
Audited bean: transactionService [TransactionService]
Audited bean: accountController [AccountController]
What are common interview follow-up questions?
- What is the difference between
@Componentand@Bean? - Can a
@Servicebean be injected into another@Service? - What happens if two beans of the same type exist and you autowire by type?
- How does
@Primaryresolve ambiguity? - How does
@Qualifierwork with@Autowired? - What is the difference between field injection, constructor injection, and setter injection?
- Why is constructor injection recommended over field injection?
- What is a circular dependency and how does Spring handle it?
- How does
@Lazyaffect bean creation? - What is the difference between
@PostConstructandInitializingBean?
Visual Overview
@SpringBootApplication
|
v
SpringApplication.run()
|
v
+---------------------------------+
| 1. Create ApplicationContext |
+---------------------------------+
|
v
+---------------------------------+
| 2. Component Scanning |
| Scan com.bank.* |
| com.bank.service |
| com.bank.repository |
| com.bank.controller |
| com.bank.config |
+---------------------------------+
|
v
+---------------------------------+
| 3. Register BeanDefinitions |
| accountService -> singleton |
| accountRepository -> singleton |
| accountController -> singleton |
+---------------------------------+
|
v
+---------------------------------+
| 4. Auto-Configuration |
| DataSource, JPA, Jackson, etc. |
+---------------------------------+
|
v
+---------------------------------+
| 5. Instantiate + Wire Beans |
| Constructor injection |
| @PostConstruct callbacks |
+---------------------------------+
|
v
Application Ready
Bean Lifecycle
==============
Constructor
|
v
Dependency Injection (setters / fields)
|
v
Aware Interfaces (BeanNameAware, ApplicationContextAware)
|
v
BeanPostProcessor.postProcessBeforeInitialization()
|
v
@PostConstruct
|
v
InitializingBean.afterPropertiesSet()
|
v
Custom init-method
|
v
BeanPostProcessor.postProcessAfterInitialization()
|
v
=== BEAN IS READY ===
|
v (on context shutdown)
@PreDestroy
|
v
DisposableBean.destroy()
|
v
Custom destroy-method
Key Takeaway
ApplicationContext is the heart of every Spring application. It is the IoC container that takes over the job of creating objects, wiring them together, and managing their lifecycle. Instead of scattering new calls throughout your code, you declare what each class needs, and the container provides it. This single change, giving control to the framework, makes your banking application loosely coupled, testable, and easy to reconfigure.
Component scanning is how ApplicationContext discovers your beans automatically. When Spring Boot starts, it reads the package of the class annotated with @SpringBootApplication and scans every sub-package for stereotype annotations: @Component, @Service, @Repository, @Controller. Each annotated class becomes a bean definition. The container then instantiates them in the right order, injects dependencies through constructors, and calls @PostConstruct methods so beans can initialize themselves.
The bean lifecycle is predictable and well-defined. Every bean travels the same path: construction, injection, initialization callbacks, active use, and destruction callbacks. Understanding this lifecycle helps you place setup code in @PostConstruct instead of the constructor, use @PreDestroy to release resources, and write custom BeanPostProcessors when you need cross-cutting behavior like auditing or metrics.
In production banking systems, you use profiles and conditional annotations to vary behavior across environments. The dev profile uses an in-memory H2 database while prod connects to PostgreSQL. You narrow component scanning in large monoliths to keep startup fast, and Spring Boot 3.4's AOT processing can eliminate runtime scanning entirely for native images.
Remember one sentence: ApplicationContext is the container that creates your beans, component scanning is the mechanism that discovers them, and the lifecycle is the path every bean travels from birth to destruction.
---