How to Instantiate Spring IoC Container

In order to get the bean instances from the configuration file, we need to instantiate the Spring IoC Container which in-turn helps us reading the configurations. Spring provides two types of IoC Container implementation.

  1. Bean Factory
  2. Application Context

Bean factory is the more basic implementation of Spring IoC Container.  Application context is the more advanced implementation. Both IoC containers will be having the same Bean configurations only.

Folder Structure:

  1. Create a new Java Project  SpringCoreTutorial” and create a package for our src files com.javainterviewpoint
  2. Add the required libraries to the build path. Java Build Path ->Libraries ->Add External JARs and add the below jars.

    commons-logging-1.2.jar
    spring-beans-4.2.4.RELEASE.jar
    spring-core-4.2.4.RELEASE.jar
    spring-context-4.2.4.RELEASE.jar
    spring-expression-4.2.4.RELEASE.jar

  3. Create the Java classes Student.java and StudentLogic.java under  com.javainterviewpoint folder.
  4. Place our configuration file SpringConfig.xml in the src directory

Student.java

Our Student class will have all the student details such name, age, percentage and its corresponding POJO’s. The getStudentDetails() method will display the student information which is set.

package com.javainterviewpoint;

public class Student
{
    private String name;
    private int age;
    private int percentage;
    
    public Student()
    {
        super();
    }
    public Student(String name, int age, int percentage)
    {
        super();
        this.name = name;
        this.age = age;
        this.percentage = percentage;
    }
    
    public String getName()
    {
        return name;
    }
    public void setName(String name)
    {
        this.name = name;
    }
    public int getAge()
    {
        return age;
    }
    public void setAge(int age)
    {
        this.age = age;
    }
    public int getPercentage()
    {
        return percentage;
    }
    public void setPercentage(int percentage)
    {
        this.percentage = percentage;
    }
    
    public void getStudentDetails()
    {
        System.out.println("**Student Details**");
        System.out.println("Student Name       : "+name);
        System.out.println("Student Age        : "+age);
        System.out.println("Student Percentage : "+percentage);
    }
}

SpringConfig.xml

<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="student" class="com.javainterviewpoint.Student">
      <property name="name" value="JavaInterviewPoint"></property>
      <property name="age" value="999"></property>
      <property name="percentage" value="95"></property>
   </bean>
</beans>
  • SpringConfig.xml has the bean definitions, We have set bean id as “student” for our Student class which will act as the reference for calling our Student class.
  • Using the Spring Setter Dependency Injection <property> tag we are setting the values to the properties of the Student class.

Instantiating Spring IoC Container using BeanFactory

BeanFactory is an interface belonging to org.springframework.beans.factory.BeanFactory. We need to instantiate one of the implementations, here we will be instantiating XmlBeanFactory.

package com.javainterviewpoint;

import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.xml.XmlBeanFactory;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;

public class StudentLogic
{
    public static void main(String args[])
    {
      //Read the configuration file
        Resource resource = new ClassPathResource("SpringConfig.xml");
        //Read all the bean definition
        BeanFactory bf = new XmlBeanFactory(resource);
        //Get the Student class instance
        Student st = (Student)bf.getBean("student");
        //Print the student details
        st.getStudentDetails();
    }
}
  • In our StudentLogic class we will  Read the Configuration file(SpringConfig.xml) through Resource class
  • Bean Factory will take the resource as input to get all the bean instances.
  • Get the Student Class instance by calling the getBean() method over the bean factory.
  • The String passed to getBean() method should be equivalent to the id defined in the SpringConfig.xml
  • Call the getStudentDetails() method to display the values which we injected through the Spring Setter Dependency Injection.

Output :

**Student Details**
Student Name       : JavaInterviewPoint
Student Age        : 999
Student Percentage : 95

Instantiating Spring IoC Container using Application Context

ApplicationContext is also an interface, Here also we need to instantiate an implementation of it. We will instantiate ClassPathXmlApplicationContext implementation which builds an application context by loading an XML configuration file from the classpath. We can also specify multiple configuration files in it.

package com.javainterviewpoint;

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

public class StudentLogic
{
    public static void main(String args[])
    {
        //Read the Configuration file using ApplicationContext
        ApplicationContext applicationContext = 
                new ClassPathXmlApplicationContext("SpringConfig.xml");
        //Get the Student class instance
        Student st = (Student) applicationContext.getBean("student");
        //Print the student details
        st.getStudentDetails();        
    }
}
  • In our StudentLogic class we have read the Configuration file(SpringConfig.xml) and get all the bean definition through ApplicationContext
  • Get the Student Class instance by calling the getBean() method over the context created.
  • Call the getStudentDetails() method to display the student details injected.

Besides ClassPathXmlApplicationContext, there are several other ApplicationContext implementations provided by Spring. FileSystemXmlApplicationContext helps us loading XML configuration files from the file system or from URLs, while XmlWebApplicationContext and XmlPortletApplicationContext can be used in web and portlet applications.

Output :

Spring IoC Container Application Context

Leave a Reply

Your email address will not be published. Required fields are marked *