Spring — Factory Pattern | Code Factory

Spring Tutorial Index Page: Link

  • What is factory and use of factory?
  • We use to create object of other classes.
  • * Factory classes main aim is to they will make clients independent by returning object in the form of Interface reference.
  • * Example: DriverManager is a factory class. Connection is an interface. DriverManager.getConnection() method will return object of Connection irrespective of database. Same code is use for any database so it will making us database independent.
  • By factory we will hide object creation logic.
  • * Logger is a static factory and SessionFactory is a instance factory.
  • Some points of factory
    - Hide instantiation logic
    - By returning instance into Interface reference Factory will make clients independent irrespective of implementation
  • Many databases given implementation for Connection interface.
interface Car {
public void drive();
class CarFactory {
private CarFactory() {
public static Car getCar(String carName) {
return (Car) Class.forName(carName).newInstance();
class JLR implements Car {
public void drive() {
sop("Maximum speed is 250");
class Audi implements Car {
public void drive() {
sop("Maximum speed is 200");
class Test {
psvm(String args[]) {
Car c = CarFactory.getCar("JLR");
  • To implement factories in Spring we have 3 approaches.
  1. Spring — Static Factories
  2. Spring — Instance Factories
  3. Spring — FactoryBean




Love podcasts or audiobooks? Learn on the go with our new app.

Recommended from Medium

2D Galaxy Shooter P1: Adding a Health Power-up!

What will TOGAF 9.3 or TOGAF 10 look like?

2D Galaxy Shooter P2: Homing Missiles to the Rescue!

Wine 7.0 Install Ubuntu, Ubuntu variations and Debian

Software Products & Platforms

Inheriting Existing Mail Templates in Odoo

How to: Create a Number Guessing Game with C# and Unity

Highlights from Salesforce’s Summer ’21 Release

Salesforce Summer ’21 Release Highlights — Blog — Ad Victoriam Solutions

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Code Factory

Code Factory

More from Medium

Spring Profiles | Spring Boot Profile

Two way Encrypt/Decrypt

Benefits of Outsourcing Java Development Services

Advantages of Outsourcing Java Development Services

How Apache Camel Facilitates Your Integration Tasks: Part 2