Categories
Spring Spring Core

Static Factory Method in Spring

In our previous article we saw how to instantiate a Bean with Constructor in Spring Framework. Now we will look at how we can instantiate a Static Factory Method. 

Instantiate a Static Factory Method in Java 

public class EmployeeController{
	private static EmployeeController employeeController = new EmployeeController();
	public static EmployeeController getInstance(){
		return employeeController;
}
}

In a plain Java application we can instantiate the above Static Factory class as like below from another class member.

EmployeeController empController = EmployeeController.getInstance();

Instantiate a Static Factory Method in Spring

In a Spring application we can instantiate the same Static Factory class is like below by defining Bean Definition.

<bean id=”employeeController” class=”net.geekcoders.EmployeeController” factory-method=”getInstance”>
</bean>

In the article we are going to learn how we can Instantiate Static Factory Method with arguments in detailed step by step procedure. 

Instantiate Static Factory Method with Parameters

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 : Right-click on Project and create a package named net.geekcoders.

Step 5 : Create a main class named EmployeeStarter in net.geekcoders package. 

As this is a Spring core project we should have a class with the main method to execute the application.

Step 6 : Add below code in EmployeeController class.

package net.geekcoders;

public class EmployeeController {
	private Employee employee;
	private EmployeeController() {}
	private static EmployeeController employeeController = new EmployeeController(); 
	
	public static EmployeeController getInstance(Employee employee, String name, int age, String role) {
		employeeController.setEmployee(employee);
		employeeController.getEmployee().setName(name);
		employeeController.getEmployee().setAge(age);
		employeeController.getEmployee().setRole(role);
		return employeeController;
	}
	
	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 Static Factory method 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 Static Factory Method given.

Step 7 : 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 8 : Right click on src folder and create a file and name it as applicationContext.xml

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

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

	<bean id="employeeController" class="net.geekcoders.EmployeeController" factory-method="getInstance">
		<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>

</beans>

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 : 

Class Fully Qualified Static Factory class

Factory-method Provide getInstance static factory method. Spring will call this method instead of calling Constructor args.

Constructor-arg providing constructor arguments to the Static Factory method.

Name : Name of the argument in constructor

Ref : Reference to the another bean in Configuration Meta-dataType : Providing type of the argument. It is not mandatory, Spring automatically defines the type of the parameter based on the class provided.

Step 9 : Open EmployeeStarter class and the below code inside the main method.

package net.geekcoders;

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

public class EmployeeStarter {

	public static void main(String[] args) {
		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 9 : Reading applicationContext.xml(Configuration Meta-data) from application class path.

Line 10 : 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 11 : 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.

That’s all for now on Instantiating the Static Factory method in Spring!!!

Happy Reading!!!

Leave a Reply

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