Loading

Quipoin Menu

Learn • Practice • Grow

spring / Factory Method in Spring
tutorial

Factory Method in Spring

Sometimes you don't want Spring to create a bean using a simple constructor. You might need a custom creation logic – that's where factory methods come in.

There are two types:

  • Static factory method – a static method that returns an instance.
  • Instance factory method – a non‑static method on an existing bean that returns another bean.

Static factory example:


public class CarFactory {
public static Car createCar() {
return new Car();
}
}
<bean id="car" class="CarFactory" factory-method="createCar"/>

Instance factory method:


public class EngineFactory {
public Engine createEngine() {
return new Engine();
}
}
<bean id="engineFactory" class="EngineFactory"/>
<bean id="engine" factory-bean="engineFactory" factory-method="createEngine"/>
Factory methods are useful when you need to integrate with legacy code or when object creation requires complex logic.
Two Minute Drill
  • Factory methods allow custom bean creation logic.
  • Static factory method: defined on a class, invoked via factory-method attribute.
  • Instance factory method: defined on an existing bean, uses factory-bean and factory-method.
  • Commonly used when constructors aren't sufficient.

Need more clarification?

Drop us an email at career@quipoinfotech.com