Open In App

Spring – Dependency Injection with Factory Method

Last Updated : 26 May, 2022
Improve
Improve
Like Article
Like
Save
Share
Report

Spring framework provides Dependency Injection to remove the conventional dependency relationship between objects. In order to inject dependencies using the factory method, we will use two of the attributes factory-method and factory-bean of bean elements.

Note: Factory methods are those methods that return the instance of the class.

  • Factory Method: These are those types of methods that are invoked to in order to inject the beans.
  • Factory Bean: These are the references of the beans by which factory methods are invoked.

Types of Factory Method

There are three types of factory methods:

  1. Static Factory Method – It is used to return the instance of its own class. Static factory methods are used for Singleton Design Pattern.
  2. Static Factory Method – It is used to return the runtime instance of another class.
  3. Non-Static Factory Method – It is used to return the runtime instance of another class.

Implementation: Here we will be injecting the dependencies using a factory pattern. For this, we will create a class and name it Geeks.java and inject this class as the dependency.

A. Static Factory Method – A returning instance of own class

In this example, we will create a singleton class Geeks.java and inject its dependency in our main class using the factory method.

Step 1: Create Geeks Class

For this create a Geeks.java. We will also define a geeksMessage() method to test the dependency injection using the factory method. Below is the code for Geeks.java class.

File: Geeks.java

Java




// Java Program to Illustrate Geeks Class
 
// Class
public class Geeks {
 
    // define a private static instance
    public static final Geeks geeks = new Geeks();
     
    // private constructor
    private Geeks() {}
     
    // this method will return the above instance
    // which was created when the class loaded in the memory
    public static Geeks getGeeks() {
        return geeks;
    }
     
    // this method is used to check the dependency injection
    public void geeksMessage() {
        System.out.println("Welcome to geeksforgeeks. DI for static factory method working good");
    }
}


Step 2: Adding Dependencies

In this step, we will add the following dependencies in pom.xml file.

File: pom.xml

XML




  <modelVersion>4.0.0</modelVersion>
  <groupId>com.geeksforgeeks</groupId>
  <artifactId>DIFactoryMethods</artifactId>
  <version>0.0.1-SNAPSHOT</version>
   
  <dependencies>
    <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-context</artifactId>
            <version>5.0.8.RELEASE</version>
    </dependency>
   </dependencies>
</project>


 
 

Step 3: Bean Configuration

 

Now, we will create application-context.xml file in our class path. We will use the application-context file to configure our bean using factory method. Below is the code for the application-context.xml file.

 

File: application-context.xml

 

XML




<?xml version="1.0" encoding="UTF-8"?> 
<beans 
  
 <!-- Note: You need to define your whole class path for your Geeks.java class -->
   
    <bean id="geeksId" class="com.geeksforgeeks.model.Geeks"
        factory-method="getGeeks">
    </bean>
   
</beans>


 
 

Step 4: Create Utility Class

 

Now, we will create a Utility class for testing our application. For this create a new class and name it TestDIFactoryMethod.java and add the following code to it.

 

File: TestDIFactoryMethod.java

 

Java




// Java Program to Illustrate TestDIFactoryMethod Class
 
// Importing required classes
import com.geeksforgeeks.model.Geeks;
import org.springframework.context.support.AbstractApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
 
// Class
public class TestDIFactoryMethod {
 
    // Main driver method
    public static void main(String[] args)
    {
 
        // Reading the application-context file
        // from the class-path
        AbstractApplicationContext context
            = new ClassPathXmlApplicationContext(
                "application-context.xml");
 
        // Spring check the blueprint for Geeks bean
        // from application-context.xml file and return it
        Geeks geeksObj = (Geeks)context.getBean("geeksId");
 
        // geeksObj contain the dependency of Geeks class
        geeksObj.geeksMessage();
    }
}


 
 

Step 5: Run the application

 

Output:

 

Fig 1 – Static Factory Method For Own Class Instance

B. Static Factory Method – Returning Instance of Another Class

 

In this example, we will inject dependencies of other classes using the static factory method.

 

Step 1: Create An Interface

 

We will create an interface and name it GeeksCourses.java and define a getCourseDetail() method in it.

 

File: GeeksCourses.java

 

Java




// Java Program to Illustrate GeeksCourses interface
 
// Interface
public interface GeeksCourses {
 
    // Print statement
    public void getCourseDetail();
}


 
 

Step 2: Create Dependent Classes

 

In this step, we will create two different classes DSACourses and JavaCourses. We will implement the GeeksCourses interface from these class and override the getCourseDetail() method. Below is the code for both the classes.

 

File: DSACourses.java

 

Java




// Java Program to Illustrate DSACourses Class
 
// Class
// Implementing GeeksCourses interface
public class DSACourses implements GeeksCourses {
 
    // Method
    // Override the getCourseDeail()
    public void getCourseDetail()
    {
        // Print statement
        System.out.println("Data Structure & Algorithms");
    }


File: JavaCourses.java

Java




// Java Program to Illustrate JavaCourses Class
 
// Class
// Implementing GeeksCources interface
public class JavaCourses implements GeeksCourses {
 
    // Method
    // Override the getCourseDeail()
    public void getCourseDetail()
    {
        // Print statement
        System.out.println("Core Java Collections");
    }
}


 
 

Step 3: Create A Factory Class

 

Now, we will create a CourseFactory class. This class will have a static factory method for the GeeksCourses interface which will return the instance of another class (DSACourses and JavaCourses). Below is the code for CourseFactory.java class.

 

File: CourseFactory.java

 

Java




// Java Program to Illustrate CourseFactory Class
 
package com.geeksforgeeks.model;
 
// Importing required classes
import com.geeksforgeeks.dao.GeeksCourses;
import com.geeksforgeeks.dao.JavaCourses;
 
// Class
public class CourseFactory {
 
    // Method
    // factory method returning instance to another class
    public static GeeksCourses getCourses()
    {
        // Returning the instance of JavaCourses class
        // One can also return the instance of DSACourses
        return new JavaCourses();
    }
}


 
 

Step 4: Bean Configuration

 

Now, we will create application-context.xml file in our classpath. We will use the application-context file to configure our bean using the factory method.

 

File: application-context.xml

 

XML




<?xml version="1.0" encoding="UTF-8"?> 
<beans 
  
 <!-- Note: You need to define your whole class path for your CourseFactory.java class -->
   
    <bean id="courseId" class="com.geeksforgeeks.model.CourseFactory"
        factory-method="getCourses">
    </bean>
   
</beans>


 
 

Step 5: Create Utility Class

 

Now, we will create a Utility class for testing our application. For this create a new class and name it TestDIFactoryMethod.java and add the following code to it.

 

File: TestDIFactoryMethod.java

 

Java




// Java Program to Illustrate TestDIFactoryMethod Class
 
// importing required classes
import com.geeksforgeeks.dao.GeeksCourses;
import org.springframework.context.support.AbstractApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
 
// Class
public class TestDIFactoryMethod {
 
    // Main driver method
    public static void main(String[] args)
    {
 
        // Reading the application-context file
        // from the class-path
        AbstractApplicationContext context
            = new ClassPathXmlApplicationContext(
                "application-context.xml");
 
        // Spring check the blueprint for GeeksCourses bean
        // from application-context.xml file and return it
        GeeksCourses geeksCourses
            = (GeeksCourses)context.getBean("courseId");
 
        // geeksCourses contain the dependency
        // of GeeksCourses class
        geeksCourses.getCourseDetail();
    }
}


 
 

Step 6: Run the application.

 

Output:

 

Fig 2 – Static Factory Method For Another Class Instance

C. Non-Static Factory Method – Returning instance of another class

 

In this example, we will inject dependencies of other classes using the non-static factory method.

 

Step 1: Create An Interface

 

We will create an interface and name it GeeksCourses.java and define a getCourseDetail() method in it.

 

File: GeeksCourses.java

 

Java




// Java Program to Illustrate GeeksCourses Interface
 
// Interface
public interface GeeksCourses
{
    // Print statement
    public void getCourseDetail();
}


 
 

Step 2: Create Dependent Classes

 

In this step, we will create two different classes DSACourses and JavaCourses. We will implement the GeeksCourses interface from these classes and override the getCourseDetail() method. Below is the code for both classes.

 

File: DSACourses.java

 

Java




// Java Program to illustrate DSACourses Class
 
// Class
// Implementing GeeksCourses interface
public class DSACourses implements GeeksCourses {
 
    // Override the getCourseDeail() method
    public void getCourseDetail()
    {
        // Print statement
        System.out.println("Data Structure & Algorithms");
    }
}


 
 

File: JavaCourses.java

 

Java




// Java Program to Illustrate JavaCourses Class
 
// Class
public class JavaCourses implements GeeksCourses {
 
    // Method
    // Override the getCourseDeail() method
    public void getCourseDetail()
    {
        // Print statement
        System.out.println("Core Java Collections");
    }
}


 
 

Step 3: Create A Factory Class

 

Now, we will create a CourseFactory class. This class will have a non-static factory method for the GeeksCourses interface which will return the instance of another class (DSACourses and JavaCourses).

 

File: CourseFactory.java

 

Java




// Java Program to Illustrate CourseFactory Class 
 
// Importing required classes
import com.geeksforgeeks.dao.DSACourses;
import com.geeksforgeeks.dao.GeeksCourses;
 
// Class
public class CourseFactory {
 
    // Non-static factory method that returns
    // the instance to another class
    public GeeksCourses getCourses()
    {
 
        // Returning the instance of JavaCourses class
        // One can also return the instance of DSACourses
        return new DSACourses();
    }
}


 
 

Step 4: Bean Configuration

 

Now, we will create an application-context.xml file in our class-path. We will use application-context file to configure our bean using factory method.

 

File: application-context.xml

 

XML




<?xml version="1.0" encoding="UTF-8"?> 
<beans 
  
 <!-- Note: You need to define your whole class path for your CourseFactory.java class -->
   
   <bean id="courseFactory" class="com.geeksforgeeks.model.CourseFactory"></bean
    <bean id="courseId" class="com.geeksforgeeks.model.CourseFactory"
        factory-method="getCourses" factory-bean="courseFactory">
    </bean>
   
</beans>


 
 

Step 5: Create Utility Class

 

Now, we will create a Utility class for testing our application. For this create a new class and name it ‘TestDIFactoryMethod.java and add the following code to it.

 

File: TestDIFactoryMethod.java

 

Java




// Java Program to Illustrate TestDIFactoryMethod Class
 
// Importing required classes
import com.geeksforgeeks.dao.GeeksCourses;
import org.springframework.context.support.AbstractApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
 
// Class
public class TestDIFactoryMethod {
 
    // Main driver method
    public static void main(String[] args)
    {
 
        // Reading the application-context file
        // from the class-path
        AbstractApplicationContext context
            = new ClassPathXmlApplicationContext(
                "application-context.xml");
 
        // Spring check the blueprint for GeeksCourses bean
        // from application-context.xml file and return it
        GeeksCourses geeksCourses
            = (GeeksCourses)context.getBean("courseId");
 
        // geeksCourses contain the dependency
        // of GeeksCourses class
        geeksCourses.getCourseDetail();
    }
}


 
 

Step 6: Run the application

 

Output:

 

Fig 2 – Non-Static Factory Method For Another Class Instance

 



Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads