Open In App
Related Articles

Spring – Static Factory Method

Improve Article
Save Article
Like Article

Static factory methods are those that can return the same object type that implements them. Static factory methods are more flexible with the return types as they can also return subtypes and primitives too. Static factory methods are used to encapsulate the object creation process. In the Spring framework if we want to create a bean using the static factory method then we could use the factory method attributes.


In this example, we will use the static factory method to create a bean and encapsulate the creation process of the bean. We will use a Student class and create different objects of this class based on the department of the students using the static factory method.

Step 1: Create a Maven Project

In this step, we will create a new maven project and make sure you will Create a simple project(skip archetype selection).

Project descriptions

Fig 1 – Project descriptions

Step 2: Adding Dependencies

Now we will add the maven dependencies to our application. Add the following dependencies to your pom.xml 




Step 3: Create A Model(Bean) Class


In this step, we will create a model class for our application. This class will have id, first_name, last_name, and department as the member variables. We will create its getter and setters method and will provide a toString() method definition. 



public class Student {
    // member variable
    private int id;
    private String first_name;
    private String last_name;
    private String department;
    // getters and setters
    public int getId() {
        return id;
    public void setId(int id) { = id;
    public String getFirst_name() {
        return first_name;
    public void setFirst_name(String first_name) {
        this.first_name = first_name;
    public String getLast_name() {
        return last_name;
    public void setLast_name(String last_name) {
        this.last_name = last_name;
    public String getDepartment() {
        return department;
    public void setDepartment(String department) {
        this.department = department;
    // toString() method
    public String toString() {
        return "Student [id=" + id + ", first_name=" + first_name + ",
                  last_name=" + last_name + ", department="
                + department + "]";


Step 4: Implementing Factory Class


In this step, we will create a StudentFactory class and in this class, we will create our factory method createStudentOfDepartmentType(String department), and provide its implementation. This class will create different Student instances depending on the department to which the student belongs.



public class StudentFactory {
    public static Student createStudentOfDepartmentType(String department) {
        // Student instance
        Student student = null;
        // if student belongs to CSE department
        if(department.equals("CSE")) {
            student = new Student();
        // if student belongs to MECH department
        else if(department.equals("MECH")) {
            student = new Student();
        // if department passed through
        // beans is not known it will
        // throw an exception
        else {
            throw new IllegalArgumentException("Unknown department");
        return student;

Step 5: Bean Configuration

In this step, we will create the spring configuration file and name it application-context.xml. We will configure our beans and use the factory-method attribute for bean creation.


<?xml version="1.0" encoding="UTF-8"?>
    <bean id="CSE" class="com.gfg.factory.StudentFactory"
        <constructor-arg value="CSE" />
    <bean id="MECH" class="com.gfg.factory.StudentFactory"
        <constructor-arg value="MECH" />


Step 6: Creating Utilities Class


Now, we will create a Utility class for testing our spring static factory method. For this create a new class and name it and add the following code to it.



import com.gfg.model.Student;
public class TestSpringFactoryMethod {
    public static void main(String []args) throws Exception {
        // Reading the application-context file
        // using class path of spring context xml file
        AbstractApplicationContext context = new ClassPathXmlApplicationContext("application-context.xml");
        // Spring check the blueprint for Student bean
        // from application-context.xml file and return it
        Student computer_student = (Student)context.getBean("CSE");
        Student mechanical_student = (Student)context.getBean("MECH");


Run the application as Java Application.


Whether you're preparing for your first job interview or aiming to upskill in this ever-evolving tech landscape, GeeksforGeeks Courses are your key to success. We provide top-quality content at affordable prices, all geared towards accelerating your growth in a time-bound manner. Join the millions we've already empowered, and we're here to do the same for you. Don't miss out - check it out now!

Last Updated : 14 Feb, 2023
Like Article
Save Article
Similar Reads
Complete Tutorials