Explore Topics

Spring Core Concepts

In Spring Framework, understanding Beans and ApplicationContext is key to building well-structured Java applications.

Beans

A Bean in Spring is essentially an object that is managed by the Spring IoC (Inversion of Control) container. Beans are the heart of the Spring Framework as they define the components of your application.

  • Definition: Beans are Java objects that are instantiated, assembled, and managed by the Spring container.
  • Creation: Beans can be created via XML configuration, annotations (@Component, @Service, @Repository, etc.), or Java-based configuration (@Configuration and @Bean).
  • Lifecycle: The Spring container manages the lifecycle of beans, from creation to destruction.

ApplicationContext

The ApplicationContext is the central interface to the Spring IoC container. It provides configuration information for the application and is responsible for creating and managing beans.

  • Initialization: When your application starts, the ApplicationContext is loaded, and it reads the configuration to create and configure the beans.
  • Types of ApplicationContext:
    • AnnotationConfigApplicationContext: For annotation-based configuration.
    • ClassPathXmlApplicationContext: For XML-based configuration.
    • GenericWebApplicationContext: For web applications.

Working of Beans & ApplicationContext

  • The ApplicationContext holds references to all the beans defined in your configuration.
  • When you ask for a bean, the ApplicationContext looks up the bean by its identifier or class type and provides you with an instance.
  • It also handles Dependency Injection (DI), so beans can be automatically injected with other beans as needed.

Example