IoC Containers : ApplicationContext vs BeanFactory
Ā
1. BeanFactory
- Definition: The simplest IoC container, responsible for instantiating, configuring, and managing beans.
-
Features:
- Lazy initialization (bean created only when requested).
- Lightweight, suitable for simple applications with limited resources.
- Usage (rare nowadays):
BeanFactory factory = new XmlBeanFactory(new ClassPathResource("beans.xml"));
MyService service = factory.getBean("myService", MyService.class);
2. ApplicationContext
-
Definition: A superset of
BeanFactory
with more enterprise-level features. -
Features:
- Eager initialization (beans created at startup, faster runtime access).
- Supports internationalization (i18n), event publishing, annotation-based config,
@Autowired
,@ComponentScan
. - Commonly used in all modern Spring Boot applications.
- Usage:
ApplicationContext context =
new ClassPathXmlApplicationContext("beans.xml");
MyService service = context.getBean("myService", MyService.class);
Key Difference
Feature | BeanFactory | ApplicationContext |
---|---|---|
Initialization | Lazy | Eager (by default) |
Advanced Features | ā No | ā Yes (AOP, events, i18n) |
Preferred in Spring | Rarely used | Almost always used (default in Spring Boot) |
ā
In Spring Boot ā ApplicationContext is the default IoC container (AnnotationConfigApplicationContext
/ ServletWebServerApplicationContext
).