BeanFactory and ApplicationContext

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 on BeanFactory and provides additional features like event handling, AOP support, and internationalization.
FeatureBeanFactoryApplicationContext
LoadingLazy (beans created on demand)Eager (creates singleton beans on startup)
FeaturesBasic DI containerAdvanced DI container (events, internationalization, AOP support)
Use CaseLightweight appsEnterprise apps
Example ClassXmlBeanFactory (old), DefaultListableBeanFactoryAnnotationConfigApplicationContext

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

  1. BeanFactory
    • Lightweight, lazy loading.
    • Suitable for memory-sensitive applications.
    • Does not provide advanced features like event handling or AOP.
  2. ApplicationContext
    • Richer features (i18n, events, AOP, etc.).
    • Singleton beans are instantiated at startup.
    • Recommended for most applications.

Leave a Reply