BeanFactory vs ApplicationContext
BeanFactory vs ApplicationContext is one of the first comparisons people meet when they learn how the Spring container works. Both are Spring IoC containers: they create beans and inject their dependencies. BeanFactory is the small core interface, while ApplicationContext builds on it and adds the features real applications need, such as automatic post-processor registration, events, messages and profiles. Every Spring Boot application runs on an ApplicationContext, but a BeanFactory is always working inside it.
This tutorial explains how the two interfaces relate, compares their behavior feature by feature, and runs both side by side so you can see the differences in the log. It also shows which context types Spring Boot creates and how to access the context from your own code when you really need it.
1. What Are BeanFactory and ApplicationContext?
The Spring IoC container is defined by two main interfaces:
BeanFactory(org.springframework.beans.factory) is the root interface for getting beans. Its key methods aregetBean(...),containsBean(...),isSingleton(...)andgetBeanProvider(...). It knows how to create and wire beans, nothing more.ApplicationContext(org.springframework.context) is aBeanFactorywith application services on top: publishing events, resolving messages, loading resources, exposing the environment and running a full startup and shutdown lifecycle.
BeanFactory is a car engine: it does the essential work. An ApplicationContext is the whole car: the same engine plus ignition, dashboard, lights and a radio. You could drive an engine on a test bench, but you would not take it on the road.2. How the Interfaces Are Related
The important point is at the bottom right: an ApplicationContext does not reimplement bean creation. Every context holds a DefaultListableBeanFactory and delegates getBean() calls to it. You can reach it with context.getAutowireCapableBeanFactory() or, on a configurable context, getBeanFactory().
3. BeanFactory vs ApplicationContext: Feature Comparison
The comparison below is between a plain DefaultListableBeanFactory used on its own and an annotation-based ApplicationContext:
| Feature | Plain BeanFactory | ApplicationContext |
|---|---|---|
| Create beans and inject dependencies | Yes | Yes |
| When singletons are created | On the first getBean(), unless you call preInstantiateSingletons() | At refresh(), for all non-lazy singletons |
BeanPostProcessor beans | Must be added by hand with addBeanPostProcessor() | Detected and registered automatically |
BeanFactoryPostProcessor beans | Must be invoked by hand | Detected and invoked automatically |
@Autowired, @PostConstruct, @Value | Ignored unless the matching post-processors are added | Processed |
| Application events | No | Yes, through ApplicationEventPublisher |
| Internationalized messages | No | Yes, through MessageSource |
Resource patterns such as classpath*:db/*.sql | No | Yes |
| Environment, profiles and property sources | No | Yes |
Lifecycle beans (SmartLifecycle start and stop) | No | Yes |
| Orderly shutdown | Call destroySingletons() yourself | close() or a JVM shutdown hook |
4. A Complete Example: Both Containers Side by Side
This plain Java program (no Spring Boot needed, only spring-context, which every Spring Boot application already has) registers the same class in both containers and logs what happens.
4.1 The Bean
package com.javabytechie.shop.container;
import jakarta.annotation.PostConstruct;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class InventoryCache {
private static final Logger log = LoggerFactory.getLogger(InventoryCache.class);
public InventoryCache() {
log.info("InventoryCache created");
}
@PostConstruct
void warmUp() {
log.info("InventoryCache warmed up");
}
}
4.2 The Comparison Program
package com.javabytechie.shop.container;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.support.DefaultListableBeanFactory;
import org.springframework.beans.factory.support.RootBeanDefinition;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.context.annotation.CommonAnnotationBeanPostProcessor;
public class ContainerComparison {
private static final Logger log = LoggerFactory.getLogger(ContainerComparison.class);
public static void main(String[] args) {
log.info("--- Plain BeanFactory ---");
DefaultListableBeanFactory factory = new DefaultListableBeanFactory();
factory.registerBeanDefinition("inventoryCache", new RootBeanDefinition(InventoryCache.class));
log.info("Definition registered, asking for the bean");
factory.getBean(InventoryCache.class);
log.info("--- BeanFactory with the annotation post-processor ---");
DefaultListableBeanFactory configured = new DefaultListableBeanFactory();
configured.addBeanPostProcessor(new CommonAnnotationBeanPostProcessor());
configured.registerBeanDefinition("inventoryCache", new RootBeanDefinition(InventoryCache.class));
configured.getBean(InventoryCache.class);
log.info("--- ApplicationContext ---");
try (AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext()) {
context.registerBean("inventoryCache", InventoryCache.class);
log.info("Definition registered, refreshing");
context.refresh();
log.info("Context refreshed, asking for the bean");
context.getBean(InventoryCache.class);
}
}
}
4.3 Output
--- Plain BeanFactory ---
Definition registered, asking for the bean
InventoryCache created
--- BeanFactory with the annotation post-processor ---
InventoryCache created
InventoryCache warmed up
--- ApplicationContext ---
Definition registered, refreshing
InventoryCache created
InventoryCache warmed up
Context refreshed, asking for the bean
Three differences are visible:
- The plain factory created the bean only when asked, and ignored
@PostConstruct, because no post-processor handled the annotation. - Adding
CommonAnnotationBeanPostProcessorby hand fixed that. This is what an annotation-based context does for you, together withAutowiredAnnotationBeanPostProcessorfor@Autowiredand@Value. - The context created and initialized the singleton during
refresh(), before anyone asked for it. The latergetBean()just returned the existing instance.
5. What ApplicationContext Adds in Practice
5.1 Events
@Component
public class StockAlerts {
private final ApplicationEventPublisher events;
public StockAlerts(ApplicationEventPublisher events) {
this.events = events;
}
public void reportLowStock(String sku, int remaining) {
events.publishEvent(new LowStockEvent(sku, remaining));
}
public record LowStockEvent(String sku, int remaining) {
}
}
Any bean with an @EventListener method for LowStockEvent receives it. See application events.
5.2 Messages
With messages.properties files on the classpath, Spring Boot auto-configures a MessageSource, and messageSource.getMessage("order.confirmed", new Object[]{orderId}, locale) returns the text in the user's language.
5.3 Resources and Environment
A context is a ResourcePatternResolver, so context.getResources("classpath*:catalog/*.json") finds matching files across all JARs. It is also EnvironmentCapable, which is how property placeholders and @Profile work.
6. Which ApplicationContext Spring Boot Uses
SpringApplication chooses the context class from the detected application type:
| Application type | Context class |
|---|---|
| Servlet web (Spring MVC) | AnnotationConfigServletWebServerApplicationContext |
| Reactive web (Spring WebFlux) | AnnotationConfigReactiveWebServerApplicationContext |
| None (batch jobs, command-line tools) | AnnotationConfigApplicationContext |
The two web variants also create and start the embedded server, as described in how Spring Boot works internally. All three hold a DefaultListableBeanFactory.
7. Accessing the Container from Your Code
Most code should never touch the container directly. When framework-level code needs it, for example to look up beans by a type only known at runtime, inject it like any other dependency:
@Component
public class ReportRegistry {
private final ListableBeanFactory beans;
public ReportRegistry(ListableBeanFactory beans) {
this.beans = beans;
}
public Set<String> reportNames() {
return beans.getBeansOfType(ReportGenerator.class).keySet();
}
}
Ask for the narrowest interface that does the job (ListableBeanFactory, ApplicationEventPublisher, ResourceLoader) rather than the whole ApplicationContext. The older ApplicationContextAware callback interface still works but ties the class to Spring for no benefit. For "give me a bean later", an ObjectProvider is usually the cleanest choice.
8. Parent and Child Contexts
Because ApplicationContext is a HierarchicalBeanFactory, contexts can form a tree. A child sees its parent's beans; a parent does not see its children's beans. Spring Boot supports this with SpringApplicationBuilder:
new SpringApplicationBuilder(SharedInfrastructureConfig.class)
.child(ShopApplication.class)
.run(args);
Hierarchies appear in some frameworks, such as Spring Cloud, and in tests. In a normal Spring Boot application there is a single context, which is simpler and should be your default.
9. When to Use Each
| Use a plain BeanFactory when | Use an ApplicationContext when |
|---|---|
You are writing framework or library code that only needs getBean() | You are building any application, with or without Spring Boot |
You need a tiny container in a test, for example to build an ObjectProvider | You need annotations, events, profiles or post-processors |
| You are exploring how Spring works internally | You want Spring Boot's auto-configuration (it always creates a context) |
As a type for injection, BeanFactory and ListableBeanFactory are perfectly fine and often better than ApplicationContext, because they ask for less.
10. Best Practices
- Run applications on an
ApplicationContext, and let Spring Boot create it. - Inject the narrowest container interface you need, such as
ApplicationEventPublisherorListableBeanFactory. - Keep business code free of
getBean(); use constructor injection orObjectProvider. - Close contexts you create yourself, for example with try-with-resources, so destroy callbacks run.
- Prefer a single context unless a framework requires a hierarchy.
11. Summary
In the BeanFactory vs ApplicationContext comparison, BeanFactory is the minimal container interface for creating and returning beans, and ApplicationContext extends it with automatic post-processor registration, eager singleton creation at refresh, events, messages, resource patterns, the environment and lifecycle management. A plain factory ignores annotations such as @PostConstruct unless you add the processors yourself, which is why applications always use a context. Spring Boot creates the right context for your application type, and inside it a DefaultListableBeanFactory still does the bean creation. Use the context for applications and inject only the narrow container interfaces your code needs.
12. References
BeanFactory vs ApplicationContext Interview Questions and Answers
Common interview questions on BeanFactory vs ApplicationContext, from basic to scenario-based, with short answers you can explain in your own words.
Q. What are the main differences between BeanFactory and ApplicationContext?
Answer: BeanFactory only creates, wires and returns beans. ApplicationContext extends it and adds automatic registration of bean post-processors and bean factory post-processors, eager creation of singletons at refresh, application events, internationalized messages, resource pattern loading, environment and profile support, and lifecycle management with orderly shutdown. Applications use an ApplicationContext.
Q. Is it accurate to say that BeanFactory is lazy and ApplicationContext is eager?
Answer: Roughly, with two qualifications. A plain DefaultListableBeanFactory creates singletons on the first getBean(), but you can call preInstantiateSingletons() to create them up front. An ApplicationContext creates non-lazy singletons during refresh(), but beans marked @Lazy, prototype beans and beans under global lazy initialization are still created on demand.
Q. Why are @PostConstruct and @Autowired ignored when you use DefaultListableBeanFactory directly?
Answer: These annotations are handled by bean post-processors: CommonAnnotationBeanPostProcessor for @PostConstruct and @PreDestroy, and AutowiredAnnotationBeanPostProcessor for @Autowired and @Value. An annotation-based context registers them automatically. A plain bean factory does not, so you must add them with addBeanPostProcessor() or the annotations have no effect.
Q. Which ApplicationContext implementation does a Spring Boot application use?
Answer: It depends on the detected application type: AnnotationConfigServletWebServerApplicationContext for Spring MVC applications, AnnotationConfigReactiveWebServerApplicationContext for WebFlux applications, and AnnotationConfigApplicationContext for non-web applications. The web variants also create and start the embedded server. Each holds a DefaultListableBeanFactory internally.
Q. How should a bean get access to the container, and when is that justified?
Answer: Inject the narrowest interface it needs, such as ListableBeanFactory, ApplicationEventPublisher or ResourceLoader, through the constructor; ApplicationContextAware also works but adds a Spring-specific callback. It is justified in framework-like code, for example a registry that discovers all beans of a type or plugins chosen at runtime. Business code should use normal injection or an ObjectProvider.
Q. In a parent-child context setup, a bean in the parent cannot inject a bean from the child. Why?
Answer: Visibility in a context hierarchy is one-way: a child resolves beans in itself first and then asks its parent, but a parent never looks into its children. Beans that several children need must live in the parent, and beans that depend on child-specific beans must live in the child. If a design needs the opposite direction, it is usually simpler to use a single context.