Categories
Spring Spring Core

Instantiating a Bean with Constructor in Spring

Bean is nothing but a normal Java class, when it is configured and managed in a IoC container of Spring it becomes a special type of Object called Bean.

Generally we can create a class with default no-args constructor or constructor with an argument, Static factory method with constructor as private access modifier or else Instance factory method to create an Object based on our use case.

In a plain Java, if we want an object from a normal class we use a new operator. If the class is a static factory implemented we call the public method of a class to create a new object. Same kind of scenario only we are going to use here with Spring Ioc Container and Bean Definition. Let us see how the Beans are getting created in Spring with a simple example.

Before proceeding with this article you can look at my previous articles on Naming a Bean and Spring IoC Container for Better understanding.

In this article I’m using Spring 5.2.5 version libraries and JDK 8.

Creating a Bean with a Default-Constructor

Step 1 : Create a Java Project from Eclipse(Use latest version) 

Name it EmployeeController and Click on Finish.

Your folder structure will be like the below screenshot.

Step 2 : Convert to Maven Project.

Right click on your project name → Select Configure option → Click on Convert to Maven Project and click on Finish. 

If you follow the above steps you can see your normal Java Project will be converted to Maven Project and the Pom file will get generated.

Step 3 : Add dependencies into the Pom.xml file.

We have to add Spring Framework dependencies in the Pom.xml file to make our example code working. 

We want spring-context and spring-beans jar files for this example project, to add these 

  • Goto https://mvnrepository.com/  
  • Search “Spring-beans” in the search bar. 
  • Click on Spring Beans from search results.
  • Click on 5.2.5 Release version from a table
  • Finally click on the Maven dependencies as shown below to copy

  • Goto pom.xml file from your project 
  • Create <dependencies></dependencies> tag just above the </project> tag 
  • Paste the copied maven dependency in between <dependencies> tag.
  • Follow the same approach to copy the spring-context dependency from maven repository and paste after the spring-beans dependency and save the pom.xml.

Step 4 : Create a Package

Right-click on Project and create a package named net.geekcoders

Step 5 : Starter class 

Create a main class named EmployeeStarter in net.geekcoders package. As this is a Spring core project we should have a class with main method to execute the application.

Step 6 : Create a Controller class

Create another class called EmployeeController under the same package and add a method like below

package net.geekcoders;

public class EmployeeController {
	public void addEmployee() {
		System.out.println("EmployeeController : addEmployee");
	}
}

Step 7 : Configuration Meta-Data

Right click on src folder and create a file and name it as applicationContext.xml

And copy paste the below code.

<?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
        https://www.springframework.org/schema/beans/spring-beans.xsd">

</beans>

Step 8 : Modify Configuration Meta-Data

We have to define a Bean Definition in Configuration Meta-Data in order to create a spring bean object.

<bean id="employeeController" class="net.geekcoders.EmployeeController"></bean>

ID : We have to provide an identifier to refer the object from IoC Container.

Class : This is a mandatory attribute and you have to provide a fully-qualified class name as like above.

Step 9 : Modify Starter Class

Open EmployeeStarter class and the below code inside the main method

ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
		EmployeeController controller = context.getBean("employeeController",EmployeeController.class);
		controller.addEmployee();

By adding the above code your EmployeeStarter class will become IoC container, and this Container will be responsible to Create bean objects by reading configuration meta-data. We can later use that object for our application use cases.

Line 1 : Reading applicationContext.xml(Configuration Meta-data) from application class path.

Line 2 : Returning an Instance of EmployeeController from IoC container. This creation of Object will be based on how we have defined the Bean Definition in applicationContext.xml file.

Line 3 : Calling the addEmployee method from EmployeeController class to make use of its feature.

Step 10 : Your final folder structure will look like this.

Now run the program you are able to see the below output in console.

We saw the above example with no-arg constructor or default constructor of EmployeeController class. What if our EmployeeController class has a constructor with args?

Creating a Bean with a Constructor args :

Step 1 : Add below code in EmployeeController class.

package net.geekcoders;

public class EmployeeController {
	private Employee employee;
	public EmployeeController(String name, int age, String role, Employee employee) {
		this.setEmployee(employee);
		this.getEmployee().setName(name);
		this.getEmployee().setAge(age);
		this.getEmployee().setRole(role);
	}
	
	public void addEmployee() {
		
		System.out.println("EmployeeController : Name :"+this.getEmployee().getName()+" Age:"+this.getEmployee().getAge()+" Role :"+this.getEmployee().getRole());
	}

	public Employee getEmployee() {
		return employee;
	}

	public void setEmployee(Employee employee) {
		this.employee = employee;
	}
}

Now you have a constructor with Employee object, name, age and role as a parameter in EmployeeController class.

We shall see how the configuration meta-data is getting transformed based on the constructor given. 

Step 2 : Create Employee class in the same package.

package net.geekcoders;

public class Employee {
	private String name;
	private int age;
	private String role;
	// getters and setters will goes here
}

Step 3 : Modify Configuration Meta-Data

To create a bean with constructor args you have to provide constructor args from meta-data as like below. IoC container will pass parameters to the constructor of the EmployeeController class and create a Bean Object. 

Edit the applicationContext.xml file in your application code. 

<bean id="employeeController" class="net.geekcoders.EmployeeController">
		<constructor-arg name="employee" ref="employee"></constructor-arg>
		<constructor-arg name="name" value="Sundar" type="String"></constructor-arg>
		<constructor-arg name="age" value="1" type="int"></constructor-arg>
		<constructor-arg name="role" value="Developer" type="String"></constructor-arg>
	</bean>
	
	<bean id="employee" class="net.geekcoders.Employee"></bean>

Have you noticed, we have added another bean definition with employee as an identifier.

Constructor from EmployeeController is accepting an Employee object as one of the parameters. We cannot pass an Object like String or int args in Spring so we have to add Bean definition for Employee class and then refer from employeeController bean definition. 

Key Terms in the above Bean Definition : 

Constructor-arg providing constructor arguments to the Bean.

Name : Name of the argument in constructor

Ref : Reference to the another bean in Configuration Meta-data

Type : Providing type of the argument. It is not mandatory, Spring automatically defines the type of the parameter based on the class provided.

Executing the program from EmployeeStarter class will produce the below output

Kudos!!! Now you have created a Spring Core application with a constructor and its working fine. 

Thank you for Reading!!!

3 replies on “Instantiating a Bean with Constructor in Spring”

Leave a Reply

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