00:00

BeanFactory vs ApplicationContext

Last updated:

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 are getBean(...), containsBean(...), isSingleton(...) and getBeanProvider(...). It knows how to create and wire beans, nothing more.
  • ApplicationContext (org.springframework.context) is a BeanFactory with application services on top: publishing events, resolving messages, loading resources, exposing the environment and running a full startup and shutdown lifecycle.
Analogy: A 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

BeanFactory and ApplicationContext interface hierarchyBeanFactory is the root interface. ListableBeanFactory adds listing beans by type, and HierarchicalBeanFactory adds a parent factory. ApplicationContext extends both and also MessageSource, ApplicationEventPublisher, ResourcePatternResolver and EnvironmentCapable. ConfigurableApplicationContext adds refresh and close. Concrete contexts such as AnnotationConfigApplicationContext and Spring Boot's AnnotationConfigServletWebServerApplicationContext implement it, and each holds a DefaultListableBeanFactory inside that does the actual bean creation. BeanFactory getBean, containsBean ListableBeanFactory find beans by type HierarchicalBeanFactory parent factory ApplicationContext + MessageSource, ApplicationEventPublisher, ResourcePatternResolver, EnvironmentCapable ConfigurableApplicationContext refresh(), close() DefaultListableBeanFactory does the real work inside every context contains
ApplicationContext extends BeanFactory and adds services; every context delegates bean creation to an internal DefaultListableBeanFactory.

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:

FeaturePlain BeanFactoryApplicationContext
Create beans and inject dependenciesYesYes
When singletons are createdOn the first getBean(), unless you call preInstantiateSingletons()At refresh(), for all non-lazy singletons
BeanPostProcessor beansMust be added by hand with addBeanPostProcessor()Detected and registered automatically
BeanFactoryPostProcessor beansMust be invoked by handDetected and invoked automatically
@Autowired, @PostConstruct, @ValueIgnored unless the matching post-processors are addedProcessed
Application eventsNoYes, through ApplicationEventPublisher
Internationalized messagesNoYes, through MessageSource
Resource patterns such as classpath*:db/*.sqlNoYes
Environment, profiles and property sourcesNoYes
Lifecycle beans (SmartLifecycle start and stop)NoYes
Orderly shutdownCall destroySingletons() yourselfclose() 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

InventoryCache.java
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

ContainerComparison.java
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

Console
--- 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:

  1. The plain factory created the bean only when asked, and ignored @PostConstruct, because no post-processor handled the annotation.
  2. Adding CommonAnnotationBeanPostProcessor by hand fixed that. This is what an annotation-based context does for you, together with AutowiredAnnotationBeanPostProcessor for @Autowired and @Value.
  3. The context created and initialized the singleton during refresh(), before anyone asked for it. The later getBean() just returned the existing instance.

5. What ApplicationContext Adds in Practice

5.1 Events

StockAlerts.java
@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 typeContext 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:

ReportRegistry.java
@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:

ShopLauncher.java
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 whenUse 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 ObjectProviderYou need annotations, events, profiles or post-processors
You are exploring how Spring works internallyYou 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 ApplicationEventPublisher or ListableBeanFactory.
  • Keep business code free of getBean(); use constructor injection or ObjectProvider.
  • 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