Javatpoint Logo
Javatpoint Logo

Dependency Injection with Factory Method in Spring

Spring framework provides facility to inject bean using factory method. To do so, we can use two attributes of bean element.

  1. factory-method: represents the factory method that will be invoked to inject the bean.
  2. factory-bean: represents the reference of the bean by which factory method will be invoked. It is used if factory method is non-static.

A method that returns instance of a class is called factory method.

Factory Method Types

There can be three types of factory method:

1) A static factory method that returns instance of its own class. It is used in singleton design pattern.

2) A static factory method that returns instance of another class. It is used instance is not known and decided at runtime.

3) A non-static factory method that returns instance of another class. It is used instance is not known and decided at runtime.


Type 1

Let's see the simple code to inject the dependency by static factory method.

Let's see the full example to inject dependency using factory method in spring. To create this example, we have created 3 files.

  1. A.java
  2. applicationContext.xml
  3. Test.java
A.java

This class is a singleton class.

applicationContext.xml
Test.java

This class gets the bean from the applicationContext.xml file and calls the msg method.

Output:

private constructor
factory method
hello user

Type 2

Let's see the simple code to inject the dependency by static factory method that returns the instance of another class.

To create this example, we have created 6 files.

  1. Printable.java
  2. A.java
  3. B.java
  4. PrintableFactory.java
  5. applicationContext.xml
  6. Test.java
Printable.java
A.java
B.java
PrintableFactory.java
applicationContext.xml
Test.java

This class gets the bean from the applicationContext.xml file and calls the print() method.

Output:

hello a

Type 3

Let's see the example to inject the dependency by non-static factory method that returns the instance of another class.

To create this example, we have created 6 files.

  1. Printable.java
  2. A.java
  3. B.java
  4. PrintableFactory.java
  5. applicationContext.xml
  6. Test.java

All files are same as previous, you need to change only 2 files: PrintableFactory and applicationContext.xml.

PrintableFactory.java
applicationContext.xml

Output:

hello a





Youtube For Videos Join Our Youtube Channel: Join Now

Feedback


Help Others, Please Share

facebook twitter pinterest

Learn Latest Tutorials


Preparation


Trending Technologies


B.Tech / MCA