Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Difference between Application context and Beanfactory in Spring framework
The Spring framework provides two IoC (Inversion of Control) containers for managing, configuring, and manipulating beans − BeanFactory and ApplicationContext.
The ApplicationContext interface extends BeanFactory to provide additional enterprise-level functionality. In modern Spring versions, ApplicationContext has largely replaced BeanFactory, though BeanFactory still exists for backward compatibility.
Since Spring 2.0 and above, the BeanPostProcessor extension point is used extensively. If you use BeanFactory directly, some features such as AOP proxying and transaction management will not work without extra manual configuration.
BeanFactory
BeanFactory is the simplest IoC container. It uses lazy loading − beans are created only when getBean() is called. It provides basic dependency injection support but lacks advanced features like event publishing and annotation-based configuration.
Example
BeanFactory factory = new XmlBeanFactory(
new ClassPathResource("beans.xml")
);
// Bean is created only at this point (lazy)
MyBean bean = (MyBean) factory.getBean("myBean");
ApplicationContext
ApplicationContext is the more advanced container. It uses eager loading − all singleton beans are instantiated at container startup. It supports annotation-based configuration, event publishing, internationalization, and automatic BeanPostProcessor registration.
Example
ApplicationContext context = new ClassPathXmlApplicationContext(
"beans.xml"
);
// Bean was already created at startup (eager)
MyBean bean = context.getBean(MyBean.class);
Key Differences
| Feature | BeanFactory | ApplicationContext |
|---|---|---|
| Implementations | XmlBeanFactory |
ClassPathXmlApplicationContext, FileSystemXmlApplicationContext, AnnotationConfigApplicationContext
|
| Annotation Support | No | Yes |
| Bean Instantiation | Lazy − when getBean() is called |
Eager − at container startup |
| Event Publishing | Not supported | Supported via ApplicationEvent
|
| Loading Mechanism | Lazy loading | Eager (aggressive) loading |
| AOP Support | Requires manual configuration | Built-in support |
| Internationalization (i18n) | Not supported | Supported via MessageSource
|
Conclusion
ApplicationContext is the preferred IoC container for most Spring applications as it provides eager loading, annotation support, event publishing, and AOP out of the box. BeanFactory is lighter but lacks these advanced features and is mainly retained for backward compatibility.
