What is Spring IOC Container with Example

In this blog post, we will explore the Spring IoC container, its configuration, usage, and examples. We'll cover the following topics:
  1. What Is the Spring Container?
  2. What is Configuration Metadata?
  3. How to Create a Spring Container?
  4. How to Retrieve Beans from Spring Container?
  5. Create Spring IoC Container XML Config Example
  6. Create Spring IoC Container Java Config Example

What Is the Spring Container?

The Spring container is a core component of the Spring Framework. It is responsible for creating and managing the lifecycle and configuration of application objects (beans). The container reads configuration metadata to know how to instantiate, configure, and assemble these beans. This metadata can be supplied in various forms, such as XML, annotations, or Java code.

Responsibilities of the IoC Container

  • Instantiating beans: Creating instances of the beans defined in the configuration.
  • Wiring beans: Managing dependencies between beans.
  • Configuring beans: Setting properties and managing initialization and destruction callbacks.
  • Managing the bean lifecycle: Handling the complete lifecycle of a bean from creation to destruction.

Spring provides two main types of containers:

  1. BeanFactory: The simplest container providing basic dependency injection features.
  2. ApplicationContext: An enhanced container providing more enterprise-specific functionality such as event propagation, declarative mechanisms to create a bean, and various ways to look up.

The org.springframework.beans and org.springframework.context packages are fundamental to the Spring Framework’s IoC container.

How the Spring IoC Container Works

  1. Read Dependency and Configuration Metadata: The Spring IoC container reads configuration metadata, which can be supplied in XML, annotations, or Java-based configurations.
  2. Create Dependency Objects and Inject Them: Based on the configuration metadata, the container creates and injects dependencies into business objects (POJOs).

What is Configuration Metadata?

Configuration metadata is how you instruct the Spring container about the objects it should manage. It defines how beans are created, configured, and assembled within the Spring IoC container. There are three primary ways to provide configuration metadata to the Spring container:

  1. XML-based configuration: The traditional way to define beans and dependencies in XML files.
  2. Annotation-based configuration: Uses annotations in Java classes to define beans and their dependencies.
  3. Java-based configuration: Uses Java classes annotated with @Configuration and methods annotated with @Bean to define beans and dependencies.

How to Create a Spring Container?

Spring provides various implementations of the ApplicationContext interface, each suited for different scenarios. Here are the common ones:

  1. AnnotationConfigApplicationContext: Used for standalone Java applications with annotation-based configuration.
  2. ClassPathXmlApplicationContext: Used for standalone applications with XML configuration loaded from the classpath.
  3. FileSystemXmlApplicationContext: Similar to ClassPathXmlApplicationContext, but the XML configuration file can be loaded from anywhere in the file system.
  4. AnnotationConfigWebApplicationContext: Used for web applications with annotation-based configuration.
  5. XmlWebApplicationContext: Used for web applications with XML configuration.

Example: Creating a Spring Container

Using XML Configuration:

ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");

Using Java Configuration:

AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(AppConfig.class);

How to Retrieve Beans from Spring Container?

Both BeanFactory and ApplicationContext provide the getBean() method to retrieve beans from the Spring container.

ApplicationContext getBean() Example

ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
HelloWorld obj = (HelloWorld) context.getBean("helloWorld");

BeanFactory getBean() Example

XmlBeanFactory factory = new XmlBeanFactory(new ClassPathResource("beans.xml"));
HelloWorld obj = (HelloWorld) factory.getBean("helloWorld");

Creating a Spring Container with XML Configuration

Step 1: Create a Maven Project

Add the necessary Spring dependencies to your pom.xml file:

<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <groupId>net.javaguides.spring</groupId>
    <artifactId>spring-ioc-example</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <properties>
        <maven.compiler.target>17</maven.compiler.target>
        <maven.compiler.source>17</maven.compiler.source>
    </properties>
    <dependencies>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-context</artifactId>
            <version>6.0.6</version>
        </dependency>
    </dependencies>
</project>

Step 2: Define Spring Beans in XML

Create an applicationContext.xml file in the src/main/resources directory:

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
           http://www.springframework.org/schema/beans/spring-beans.xsd">

    <bean id="greetingService" class="net.javaguides.spring.ioc.GreetingService">
        <property name="message" value="Hello, Spring XML Configuration!"/>
    </bean>
</beans>

Step 3: Create a Java Class to Retrieve Beans

package net.javaguides.spring.ioc;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class Application {
    public static void main(String[] args) {
        ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
        GreetingService greetingService = (GreetingService) context.getBean("greetingService");
        greetingService.getMessage();
    }
}

GreetingService.java:

package net.javaguides.spring.ioc;

public class GreetingService {
    private String message;

    public void setMessage(String message) {
        this.message = message;
    }

    public void getMessage() {
        System.out.println("Message: " + message);
    }
}

Creating a Spring Container with Java Configuration

Step 1: Create a Maven Project

Use the same Maven project setup as the XML example.

Step 2: Define Spring Beans in Java

Create an AppConfig.java file:

package net.javaguides.spring.ioc;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
public class AppConfig {
    @Bean
    public GreetingService greetingService() {
        GreetingService greetingService = new GreetingService();
        greetingService.setMessage("Hello, Spring Java Configuration!");
        return greetingService;
    }
}

Step 3: Create a Java Class to Retrieve Beans

package net.javaguides.spring.ioc;

import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;

public class Application {
    public static void main(String[] args) {
        ApplicationContext context = new AnnotationConfigApplicationContext(AppConfig.class);
        GreetingService greetingService = (GreetingService) context.getBean("greetingService");
        greetingService.getMessage();
        ((AnnotationConfigApplicationContext) context).close();
    }
}

GreetingService.java:

package net.javaguides.spring.ioc;

public class GreetingService {
    private String message;

    public void setMessage(String message) {
        this.message = message;
    }

    public void getMessage() {
        System.out.println("Message: " + message);
    }
}

Summary

In this blog post, we covered the basics of the Spring IoC container, including how it works, what configuration metadata is, and how to create and retrieve beans from the container using both XML and Java-based configurations. This flexibility allows you to choose the most suitable configuration method for your project's needs. By understanding these concepts, you can effectively leverage the power of Spring to manage your application's dependencies and configurations.

Comments

  1. Very nicely explained Spring IOC container.

    ReplyDelete
  2. Clearly and useful !

    ReplyDelete
  3. Can you please explain the difference between bean factory and application context in detail.

    ReplyDelete
  4. Ur contents r very helpful ...
    Please make some videos on microservices and angular lastest for beginners

    ReplyDelete

Post a Comment

Leave Comment