In this post, we will learn to implement a factory method pattern in Spring Boot. This Factory Method Design Pattern comes under the creational Design Pattern.
The benefit of this pattern is that we can create an instance of objects without exposing the object creation logic to the client.
Now, let’s take a simple example.
Suppose, we have multiple banks and they all have different interest rates.
To implement the factory method pattern in spring boot, we can create a common interface and get the interest rates of banks by providing the name of the bank.
Create an interface
public interface Bank {
public double getInterestRate();
}
Implementation of Bank interface
I am creating three bank classes that implement the Bank interface so that they all share the same getInterestRate()
method.
@Component
public class NabilBank implements Bank {
@Override
public double getInterestRate() {
return 10.12;
}
}
@Component
public class ICICIBank implements Bank {
@Override
public double getInterestRate() {
return 12.45;
}
}
@Component
public class HDFCBank implements Bank {
@Override
public double getInterestRate() {
return 9;
}
}
Create a factory class
@Component
public class BankFactory {
@Autowired
private HDFCBank hdfcBank;
@Autowired
private NabilBank nabilBank;
@Autowired
private ICICIBank iciciBank;
public Bank getBank(String bankName) {
if (bankName == null)
return null;
if (bankName.equals("hdfc")) {
return hdfcBank;
} else if (bankName.equals("nabil")) {
return nabilBank;
} else if (bankName.equals("icici")) {
return iciciBank;
} else
return null;
}
}
Things to understand while implementing Factory Method in Spring
The important thing to note here is that many developers make a mistake while returning the instance of the implementation by creating a new object.
For example:
if (bankName.equals("hdfc")) {
return new HDFCBank();
}
Which is wrong and throws NullPointerException. Because in spring context it must be injected. All the implementation classes are Spring Component so we have to inject first and return the injected instance.
There is also one important thing to understand is that, if the underline implementation class is not a Spring Component then we can simply return the new instance by calling the constructor.
Testing
Factory method pattern test
@Service
public class MainService {
@Autowired
private BankFactory bankFactory;
public void printInterestRate() {
Bank bank = bankFactory.getBank("hdfc");
System.out.println(bank.getInterestRate());
}
}
The output will be the interest rate defined in HDFCBank.
Similarly, we can get the interest rate of other banks by providing the name of that bank in the method parameter.
Conclusion
In this post, we learned to create a factory method in Spring Boot so that we can use its component without having any issues.