1. Difference Between BeanFactory and ApplicationContext
- The
BeanFactory
is the core interface of the Spring IOC (Inversion of Control) container. It is responsible for instantiating, configuring, and managing beans. ApplicationContext
is a more advanced Spring IOC container. It builds onBeanFactory
and provides additional features like event handling, AOP support, and internationalization.
Feature | BeanFactory | ApplicationContext |
---|---|---|
Loading | Lazy (beans created on demand) | Eager (creates singleton beans on startup) |
Features | Basic DI container | Advanced DI container (events, internationalization, AOP support) |
Use Case | Lightweight apps | Enterprise apps |
Example Class | XmlBeanFactory (old), DefaultListableBeanFactory | AnnotationConfigApplicationContext |
2. Java-Based Configuration Example (No XML)
Suppose we have a simple service class:
// Service class
public class HelloService {
public void sayHello() {
System.out.println("Hello, Spring!");
}
}
Using BeanFactory
import org.springframework.beans.factory.support.DefaultListableBeanFactory;
import org.springframework.beans.factory.support.GenericBeanDefinition;
public class BeanFactoryExample {
public static void main(String[] args) {
DefaultListableBeanFactory factory = new DefaultListableBeanFactory();
// Register bean definition
GenericBeanDefinition beanDefinition = new GenericBeanDefinition();
beanDefinition.setBeanClass(HelloService.class);
factory.registerBeanDefinition("helloService", beanDefinition);
// Get bean
HelloService service = (HelloService) factory.getBean("helloService");
service.sayHello();
}
}
✅ Here, the bean is created lazily when getBean()
is called.
Using ApplicationContext
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@Configuration
class AppConfig {
@Bean
public HelloService helloService() {
return new HelloService();
}
}
public class ApplicationContextExample {
public static void main(String[] args) {
ApplicationContext context = new AnnotationConfigApplicationContext(AppConfig.class);
HelloService service = context.getBean(HelloService.class);
service.sayHello();
}
}
✅ Here, the bean is created eagerly at context initialization.
Key Points
- BeanFactory
- Lightweight, lazy loading.
- Suitable for memory-sensitive applications.
- Does not provide advanced features like event handling or AOP.
- ApplicationContext
- Richer features (i18n, events, AOP, etc.).
- Singleton beans are instantiated at startup.
- Recommended for most applications.