In this article, you will learn the differences between IoC Containers in Spring, namely Application Context and the Bean Factory in Spring Framework. The Spring IoC container is the core of the Spring Framework. It creates the class instances, wires them together, configures them, and manages their complete life cycle from creation till destruction. The Spring container uses dependency injection (DI) to manage the components that make up an application.

If you are new to Spring Framework, checkout the related articles:

What is IoC Container in Spring?

In the article, Inversion of Control and Dependency Injection in Spring I have given you a details explanations of this. In the Spring framework, we don’t create the instance of the dependencies rather the framework does this for us.

  • The IoC container is the core of the Spring Framework and is responsible for managing the lifecycle of beans and their dependencies.
  • It implements the principle of inversion of control, where the control of object creation and lifecycle management is delegated to the container.
  • There are two main types of IoC containers in Spring: BeanFactory and ApplicationContext.

IoC – Inversion of Control means, we don’t have the control to create the dependencies rather the framework does it for us. The code that is responsible for doing the dependency injection is known as IoC Container.

Java
@Service
public class StudentService {

  @Autowired
  private StudentRepository repository;
  // Other logics
}
Java
@Repository
public class StudentRepository {
    //persistence logic
}

In the above example, we don’t create the instance of StudentRepository manually, rather the spring creates it for us. Technically the Spring IoC Container creates it for us.

Inversion of Control is a technique that ensures decoupling, by transferring the objection creation job to a Container or Framework. The framework also allows us to customize the Objection creation and add custom behavior as per the developer’s needs. It is called inversion because the process is inverse where the bean creation and dependency is controlled by the container instead of the bean itself.

Advantages of IoC

  • Decoupling the objects and its executions.
  • Helps in runtime Polymorphism.
  • Better code Maintainability.
  • Easy code Testing due to loose coupling between the interfaces and implementations.

Two types of Spring IoC Containers

Spring provides the following two types of containers:

  • BeanFactory container
  • ApplicationContext container

1. What is BeanFactory in Spring?

  • The BeanFactory interface is the root interface for accessing a Spring IoC container.
  • It provides basic functionality for managing beans, such as instantiation, configuration, and dependency injection.
  • BeanFactory implementations, such as DefaultListableBeanFactory, LazyInitBeanFactory, and XmlBeanFactory, are available in Spring.

Bean factory implementations should support the standard bean lifecycle interfaces as far as possible. The BeanFactory is a central registry of application beans, their configurations, and dependencies.

The BeanFactory enables us to read bean definitions and access them using the bean factory as shown below. As you have already learned about the dependency injection before, I will only show you how to use BeanFactory as the base interface.

Java
public class TestAutowireExample {
  public static void main(String[] args) {
  
    BeanFactory beanFactory = new AnnotationConfigApplicationContext(AutowireBeanConfig.class);
    System.out.println(beanFactory.getBean(Store.class));
  }
}

The full set of initialisation methods and their standard order for a managed bean is:

  • BeanNameAware’s setBeanName
  • BeanClassLoaderAware’s setBeanClassLoader
  • BeanFactoryAware’s setBeanFactory
  • EnvironmentAware’s setEnvironment
  • EmbeddedValueResolverAware’s setEmbeddedValueResolver
  • ResourceLoaderAware’s setResourceLoader (only applicable when running in an application context)
  • ApplicationEventPublisherAware’s setApplicationEventPublisher (only applicable when running in an application context)
  • MessageSourceAware’s setMessageSource (only applicable when running in an application context)
  • ApplicationContextAware’s setApplicationContext (only applicable when running in an application context)
  • ServletContextAware’s setServletContext (only applicable when running in a web application context)
  • postProcessBeforeInitialization methods of BeanPostProcessors
  • InitializingBean’s afterPropertiesSet
  • a custom init-method definition
  • postProcessAfterInitialization methods of BeanPostProcessors

On shutdown of a bean factory, the following lifecycle methods apply:

  • postProcessBeforeDestruction methods of DestructionAwareBeanPostProcessors
  • DisposableBean’s destroy
  • a custom destroy-method definition

3. What is ApplicationContext in Spring

The ApplicationContext is a central interface to provide configuration for an application. This is read-only while the application is running but may be reloaded if the implementation supports this.

  • ApplicationContext is a sub-interface of the BeanFactory and provides enhanced functionality and features.
  • It is a more advanced container that supports additional enterprise-specific features, such as internationalization, event propagation, and application lifecycle events.
  • ApplicationContext implementations, such as ClassPathXmlApplicationContext, AnnotationConfigApplicationContext, and WebApplicationContext, are commonly used in Spring applications.
Java
public class TestAutowireExample {
  public static void main(String[] args) {

    ApplicationContext context = new AnnotationConfigApplicationContext(AutowireBeanConfig.class);
    System.out.println(context.getBean(Store.class));
  }
}

An ApplicationContext provides:

  • Bean factory methods for accessing application components. Inherited from ListableBeanFactory.
  • The ability to load file resources in a generic fashion. Inherited from the ResourceLoader interface.
  • The ability to publish events to registered listeners. Inherited from the ApplicationEventPublisher interface.
  • The ability to resolve messages, supporting internationalization. Inherited from the MessageSource interface.
  • Inheritance from a parent context. Definitions in a descendant context will always take priority. This means, for example, that a single parent context can be used by an entire web application, while each servlet has its own child context that is independent of that of any other servlet.

I recommend using the ApplicationContext wherever needed instead of the BeanFactory, as some of its implementations classes have been deprecated in Spring 5.x.

Conclusion:

I have given you a details explanation of IoC containers in Springi.e. ApplicationContext and BeanFactory. BeanFactory works first doing the heavy lifting jobs and then the ApplicationContext adds extra features like message source reading, message translations and etc.

  • Use BeanFactory when:
    • You require lightweight IoC container functionality.
    • You have memory constraints and need lazy initialization of beans.
  • Use ApplicationContext when:
    • You require advanced features like internationalization, event propagation, and application context hierarchies.
    • You prefer eager initialization of singleton beans for improved performance.
    • Avoid using it in real world project, unless you know what you are doing.
By |Last Updated: April 2nd, 2024|Categories: Spring Framework|