How to Create and Configure Beans in the Spring IoC Container

Spring provides a powerful IoC container to manage the beans which makes up an application. In Spring, Beans can be configured in the Spring IoC container through XML files, properties files, annotations. Spring allows you to configure your beans in one or more bean configuration files. For a simple application we can have a single configuration file whereas in the case of a large application a single file becomes unmanageable and hence we can separate them into multiple configuration file based on their functionality (DAO, Controllers etc.). Lets create a Student Application, through it we will learn how to create and configure beans in Spring IoC Container.

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

Creating a Bean Class

Here our Student class act as a bean, containing 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);
    }
}

 Creating and Declaring the Beans in Bean Configuration file (Setter Injection)

In order to declare beans in the Spring IoC container via XML, we must create an XML configuration file (SpringConfig.xml). The configuration file must be put in the src directory.

<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</value>
      </property>
      <property name="age">
         <value>999</value>
      </property>
      <property name="percentage">
         <value>95</value>
      </property>
   </bean>
</beans>
  • Each bean should have a name or id and fully qualified class name for the Spring IoC container to instantiate it. Here our bean is the student class.
  • The Student class has String and int properties and Using the Spring Setter Dependency Injection <property> tag we are setting the values to the properties of the Student class.
  • Point to be noted here is that the <property> expects the bean to have the corresponding setter method in it.

Configure Beans via Spring Constructor Injection

We can also configure the bean properties through Spring Constructor Injection by declaring them in the <constructor-arg> tag instead of the <property> tag. In Constructor injection name attribute is not required as the Constructor arguments are position based. The above Setter Injection can be changed to Constructor Injection like below.

 <bean id="student" class="com.javainterviewpoint.Student">
      <constructor-arg>
         <value>JavaInterviewPoint</value>
      </constructor-arg>
      <constructor-arg>
         <value>999</value>
      <constructor-arg>
      <constructor-arg>
         <value>95</value>
      <constructor-arg>
   </bean>

Instantiating Spring IoC Container – Application Context

Since ApplicationContext is an interface, Here 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.

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.

Output :

Upon running our StudentLogic class we will be getting the below output.

Spring IoC Container Application Context

Defining Bean Values directly

In the above code we have injected values of Bean Property using the <value> tag.

<bean id="student" class="com.javainterviewpoint.Student">
      <property name="name">
         <value>JavaInterviewPoint</value>
      </property>
      <property name="age">
         <value>999</value>
      </property>
      <property name="percentage">
         <value>95</value>
      </property>
   </bean>

Instead you can directly assign the value to the bean property using the “value” attribute of the <property> tag.

<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>

Note :

Setter Injection overrides the Constructor Injection

Suppose while declaring the bean in the bean configuration file, we are including the both <property> tag (Setter Injection) and <constructor-arg> tag  (Constructor Injection) like below

<bean id="student" class="com.javainterviewpoint.Student">
      <property name="name" value="JavaInterviewPoint-Setter"></property>
      <property name="age" value="1111"></property>
      <property name="percentage" value="11"></property>
      
      <constructor-arg>
         <value>JavaInterviewPoint-Constructor</value>
      </constructor-arg>
      <constructor-arg>
         <value>2222</value>
      <constructor-arg>
      <constructor-arg>
         <value>22</value>
      <constructor-arg>
</bean>

Then uppon running our StudentLogic class we will be getting the output like

**Student Details**
Student Name       : JavaInterviewPoint-Setter
Student Age        : 1111
Student Percentage : 11

The Setter Injection overrides the Constructor Injection.

Leave a Reply

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