ApplicationContext
About
In Spring, ApplicationContext is the central interface for accessing Spring container functionalities. It builds on BeanFactory, providing advanced features like event propagation, internationalization, and declarative bean creation using annotations.
Modern Spring applications, especially Spring Boot applications, rely on ApplicationContext as the default container for managing beans and dependencies.
Spring applications automatically create and use an ApplicationContext to manage all registered beans and services. It is the backbone of modern Spring-based applications, particularly Spring Boot.
Use
ApplicationContextin ALL modern Spring applications (Spring Boot, MVC, REST APIs).Use
BeanFactoryONLY for lightweight applications where dependency injection alone is needed.For web applications, use
WebApplicationContextinstead ofBeanFactory.
Features of ApplicationContext (Compared to BeanFactory)
ApplicationContext (Compared to BeanFactory)Feature
ApplicationContext
Full Dependency Injection (DI)
Supports full DI, including constructor, setter, and field injection.
Bean Lifecycle Management
Handles initialization, destruction, and lifecycle callbacks.
Annotation-Based Configuration
Supports @Component, @Bean, @Service, etc.
AOP Support
Supports Aspect-Oriented Programming (AOP) via Spring proxies.
Event Handling
Supports publishing & listening to custom and built-in Spring events.
Internationalization (i18n)
Provides message source support for different locales.
Environment and Property Support
Reads properties from .properties and .yaml files.
Resource Loading
Supports file, URL, classpath, and stream-based resources.
Spring Boot Integration
Essential for Spring Boot applications (SpringApplication.run()).
How ApplicationContext Works Internally?
ApplicationContext Works Internally?The Lifecycle of ApplicationContext
ApplicationContextWhen a Spring application starts, ApplicationContext goes through several phases:
Instantiation – A concrete implementation of
ApplicationContextis created.Configuration Parsing – Reads XML, Java-based, or annotation-based configurations.
Bean Definition Registration – Stores metadata about beans and their dependencies.
Bean Instantiation & Dependency Injection – Creates bean instances and injects dependencies.
Post-Processing – Applies custom logic through
BeanPostProcessor.Application Ready State – The application is fully initialized and ready to process requests.
Shutdown & Cleanup – Releases resources and destroys beans when the application exits.
Components in ApplicationContext
ApplicationContextBeanDefinitionRegistry
Holds metadata about all beans before they are instantiated. Stores information like bean class, scope, dependencies, lifecycle callbacks.
Example:
@Bean
public UserService userService() {
return new UserService();
}Here, Spring registers UserService in the BeanDefinitionRegistry.
BeanFactory
The core dependency injection container within ApplicationContext. Responsible for instantiating and managing bean dependencies. Unlike ApplicationContext, BeanFactory does not support AOP, events, and internationalization.
ResourceLoader
Handles loading of external resources like properties files, XML, and YAML.
Example:
Resource resource = context.getResource("classpath:application.properties");ApplicationEventPublisher
Allows publishing and subscribing to events.
Example:
context.publishEvent(new CustomEvent(this, "User Registered"));MessageSource
Supports internationalization (i18n). Loads localized messages from properties files.
Example:
String message = context.getMessage("welcome.message", null, Locale.ENGLISH);Types of ApplicationContext Implementations
ApplicationContext ImplementationsSpring provides several ApplicationContext implementations, each tailored for different use cases:
1. Annotation-Based Configuration (Modern)
✔ AnnotationConfigApplicationContext
Used for Java-based configuration (@Configuration, @Bean). Common in Spring Boot applications.
Example:
ApplicationContext context = new AnnotationConfigApplicationContext(AppConfig.class);✔ AnnotationConfigWebApplicationContext
Specially designed for web applications (Spring MVC, Spring Boot).
Example:
AnnotationConfigWebApplicationContext context = new AnnotationConfigWebApplicationContext();
context.register(AppConfig.class);2. XML-Based Configuration (Legacy, Rarely Used)
✔ ClassPathXmlApplicationContext
Loads Spring configuration from an XML file in the classpath.
Example:
ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");✔ FileSystemXmlApplicationContext
Loads Spring XML configuration from an absolute file path.
Example:
ApplicationContext context = new FileSystemXmlApplicationContext("C:/config/app.xml");3. Web-Specific Contexts
✔ WebApplicationContext
Sub-interface of ApplicationContext designed for web applications. Integrated with Spring MVC DispatcherServlet.
Example:
WebApplicationContext context = ContextLoader.getCurrentWebApplicationContext();✔ GenericWebApplicationContext
Supports both XML and annotation-based configurations. Used when creating programmatic web applications.
Functionalities of ApplicationContext
ApplicationContext1. Bean Management & Dependency Injection
ApplicationContext automatically manages beans by scanning for @Component, @Service, @Repository, and @Bean annotations. Supports constructor, setter, and field injection.
Example:
@Component
public class UserService {
private final UserRepository userRepository;
@Autowired
public UserService(UserRepository userRepository) {
this.userRepository = userRepository;
}
}2. Event Handling
ApplicationContext allows event publishing and listening for handling system-wide events. Uses ApplicationEventPublisher to dispatch events.
Example:
@Component
public class CustomEventListener {
@EventListener
public void handleEvent(ApplicationEvent event) {
System.out.println("Event received: " + event);
}
}3. Internationalization (i18n)
Supports multi-language messages via MessageSource.
Example (messages.properties file):
welcome.message = Welcome to Spring!Fetching message dynamically:
String message = context.getMessage("welcome.message", null, Locale.ENGLISH);4. Environment & Property Management
Reads properties from external files (application.properties, application.yaml).
Example:
@Value("${server.port}")
private int port;5. Resource Management
Allows loading files from classpath, filesystem, or URL.
Example: Reading a file from the classpath:
Resource resource = context.getResource("classpath:config.properties");Last updated