Skip to content
javahacks.dev
Spring Framework

Spring ApplicationContext vs BeanFactory Explained

Learn what BeanFactory and ApplicationContext each provide in Spring, what the context adds, and why application code almost always uses the context.

5 min read
Summarize in AI
Flat illustration of two options weighed side by side, with the Spring, Gradle and OpenJDK logos.

Both interfaces are the Spring container. One is the minimum, and the other is what applications run. This post follows Spring Framework 7.

What BeanFactory is

java
DefaultListableBeanFactory factory = new DefaultListableBeanFactory();
new XmlBeanDefinitionReader(factory).loadBeanDefinitions("beans.xml");
Greeter greeter = factory.getBean(Greeter.class);

BeanFactory defines getBean, containsBean, isSingleton and a few related methods. A DefaultListableBeanFactory holds bean definitions and instantiates a bean on first request, then resolves its dependencies. It does the core job of dependency injection and little else.

What ApplicationContext adds

java
try (var context = new AnnotationConfigApplicationContext(AppConfig.class)) {
    Greeter greeter = context.getBean(Greeter.class);
}

ApplicationContext extends BeanFactory through ListableBeanFactory and HierarchicalBeanFactory and adds:

CapabilityInterface or feature
EventsApplicationEventPublisher, @EventListener
Messages and i18nMessageSource
ResourcesResourceLoader, classpath: and file: URLs
EnvironmentEnvironment, profiles, property sources
LifecycleLifecycle, SmartLifecycle, shutdown hooks
Annotation support@Configuration, @ComponentScan processed automatically

It also instantiates all non-lazy singleton beans during refresh. That is the reason an invalid wiring fails at startup, with errors like no qualifying bean, instead of in the middle of a request.

Post-processors are the real difference

@Autowired, @PostConstruct, @Transactional and AOP proxies are implemented by BeanPostProcessor and BeanFactoryPostProcessor objects. A bare BeanFactory does not register them, so annotations are silently ignored unless you add the processors by hand. The context finds and registers them in refresh(). The container guide follows the whole refresh sequence.

A quick demonstration

java
@Component
class Listener {
    @EventListener
    void on(ContextRefreshedEvent e) { System.out.println("ready"); }
}

This prints ready with a context and never with a bare factory, since there is no event machinery. The same goes for @Value("${app.name}"), which needs the environment.

Which one in practice

Spring Boot builds an ApplicationContext (AnnotationConfigServletWebServerApplicationContext for a servlet app), and you inject ApplicationContext or ObjectProvider<T> when you need lookup. Prefer ObjectProvider for optional or lazy access, as it is a typed handle without the whole context. A getBean call in business code is a hint that the dependency should be injected, because it turns the container into a service locator.

java
@Service
class Exporter {
    private final ObjectProvider<Compressor> compressor;
    Exporter(ObjectProvider<Compressor> compressor) { this.compressor = compressor; }
    void export() { compressor.ifAvailable(c -> c.compress()); }
}

Who calls your lifecycle methods

@PostConstruct, @Autowired and @Transactional are not features of the language or of the bean factory. They work because BeanPostProcessor implementations see each bean as it is created: one handles the @PostConstruct and @Resource annotations, another handles @Autowired, another wraps beans in proxies. A bare DefaultListableBeanFactory registers none of them, which is why the same class works in an application and silently does nothing when you build a factory by hand in a test. That is the practical meaning of "ApplicationContext adds features": it registers the processors that make annotations work.

What refresh() does

When you create a context, refresh() runs a fixed sequence: it prepares the environment, loads the bean definitions, lets BeanFactoryPostProcessor instances modify those definitions (this is where @Configuration classes are processed and where property placeholders are resolved), registers the bean post-processors, initializes the message source and the event multicaster, instantiates all non-lazy singletons, and publishes ContextRefreshedEvent. Knowing the order explains many startup errors. A bean that needs a placeholder value before the placeholder configurer has run, or a BeanFactoryPostProcessor that depends on an ordinary bean and so forces it to be created too early, shows up as a warning that the bean is not eligible for processing by all post-processors.

Events and other services

The context is also an ApplicationEventPublisher, a MessageSource for internationalization, a ResourcePatternResolver that understands classpath*: and an Environment with profiles and properties. Publishing an event with publisher.publishEvent(new OrderPlaced(id)) decouples the sender from the listeners. Listeners are synchronous by default, running on the publisher's thread, and inside its transaction unless you use @TransactionalEventListener, which waits for the commit. People often assume events are asynchronous, and a slow listener then slows the request.

Do not use the context as a service locator

Injecting ApplicationContext and calling getBean(...) works and hides dependencies from the constructor, which makes the class hard to test and the wiring hard to read. Inject what you need. When you need a bean lazily, or several of one type, use ObjectProvider<T>, which defers creation and handles optional beans without reaching into the container. Reserve direct use of the context for framework-like code, such as a plugin loader that must look up beans by name at run time.

A quick experiment you can run

To see the difference without reading source, build a DefaultListableBeanFactory by hand, register a bean class that has an @Autowired field and a @PostConstruct method, and call getBean. The field stays null and the init method never runs. Now create an AnnotationConfigApplicationContext with the same class and call getBean. Both work. The only change is that the context registered the annotation post-processors during refresh(). Ten lines of code make the abstract statement concrete, and it is a good thing to show a colleague who thinks the two are interchangeable.

Parent and child contexts

A context can have a parent, and a bean lookup that fails in the child continues in the parent. Classic Spring MVC uses this: a root context holds services and repositories, and a child context holds the controllers of a servlet, which can see the services and not the other way around. The consequence is a bug that still appears in older applications. A bean defined in the child that you expected the parent's service to inject is invisible to it, and the failure looks like a missing bean even though the bean exists. Spring Boot uses a single context by default, which avoids the problem, and you meet hierarchies mostly in legacy WAR deployments and in some actuator setups with a separate management context.

Where you would touch BeanFactory in new code

Almost never directly, and that is the right answer for application code. The places it appears are framework-level extension points: a BeanFactoryPostProcessor that registers or changes bean definitions before anything is created, a BeanDefinitionRegistryPostProcessor that adds definitions in code, and ConfigurableListableBeanFactory when a library has to look up beans by type. If you find yourself casting the context to a factory in an ordinary service, step back and ask what the constructor should have received instead.

Where this does not apply

A BeanFactory makes sense when you embed the container in a library with strict startup or memory constraints, or write a framework extension. For anything else, use the context. The lifecycle of the beans inside either one is in the bean lifecycle. The reference chapter is The IoC Container, and the [BeanFactory Javadoc](https://docs.spring.io/spring-framework/docs/current/javadoc-api/org/springframework/beans/factory/BeanFactory.html) lists the contract.

Share

Keep reading

Get new posts by email

We send one email when a new post is published. No spam.

Unsubscribe in one click. No spam, ever.