Skip to lesson

Spring beans, factories and dependency injection as patterns

ShopLite's checkout code builds its own payment and email objects with new, so it is hard to test or change. Spring fixes this with three patterns you know: a factory, a singleton cache and constructor injection.

The container as a big factory: BeanFactory and ApplicationContext

A bean is an object that the Spring container creates, connects and keeps for you. The container is an ApplicationContext, which extends the basic BeanFactory.

Instead of calling new, ShopLite code asks the Spring container for a bean by type. In pattern terms, the container is one large Factory.

Java
// Spring Boot creates the ApplicationContext for youConfigurableApplicationContext ctx = SpringApplication.run(ShopLiteApplication.class, args);OrderService orders = ctx.getBean(OrderService.class);   // ask the factory by type

Example 1 · Asking the container for beans

Runs in: a Spring Boot project

ShopLiteApplication.javaJava
package com.shoplite;
import com.shoplite.order.OrderService;import com.shoplite.payment.PaymentGateway;import org.springframework.boot.SpringApplication;import org.springframework.boot.autoconfigure.SpringBootApplication;import org.springframework.context.ConfigurableApplicationContext;
@SpringBootApplicationpublic class ShopLiteApplication {    public static void main(String[] args) {        ConfigurableApplicationContext ctx = SpringApplication.run(ShopLiteApplication.class, args);
        // The context is a factory: ask it for an object by type        OrderService first = ctx.getBean(OrderService.class);        OrderService second = ctx.getBean(OrderService.class);        System.out.println("Same OrderService both times: " + (first == second));
        PaymentGateway gateway = ctx.getBean(PaymentGateway.class);        System.out.println("PaymentGateway bean: " + gateway.getClass().getSimpleName());    }}
Sample output
Same OrderService both times: true
PaymentGateway bean: UpiPaymentGateway

What this code does

  • SpringApplication.run builds the ApplicationContext, the factory that creates and stores every bean.
  • Two getBean calls return the same OrderService because of singleton scope. The PaymentGateway bean is whichever implementation the configuration chose.

The basic container interface is BeanFactory, whose main method is getBean; ApplicationContext adds configuration files, events and messages, and is what Spring Boot gives you. You describe each bean once, with an annotated class or a @Bean method. In normal application code you never call getBean yourself; the container uses it to wire beans together.

Singleton scope vs the Singleton pattern

Singleton scope means the container creates one instance of a bean and hands the same one to everyone who asks. It is the default scope.

Spring's singleton scope is not the Singleton pattern. Scope means one instance per container; the pattern means one per class loader, enforced by the class itself.

PricingService.javaJava
@Service                          // singleton scope by defaultpublic class PricingService { }
@Component@Scope("prototype")               // a new object every time it is requestedpublic class CartDraft { }

Example 2 · One per JVM vs one per container

ScopeDemo.javaJava
import java.util.HashMap;import java.util.Map;import java.util.function.Supplier;
// The classic Singleton pattern: one instance per JVM, enforced by the class itselfclass AppConfig {    private static final AppConfig INSTANCE = new AppConfig();
    private AppConfig() {        System.out.println("AppConfig created");    }
    static AppConfig getInstance() {        return INSTANCE;    }}
// A normal class: it has no idea how many copies existclass CartPricing {    CartPricing() {        System.out.println("CartPricing created");    }}
// A very small "container" with singleton scope: one instance per containerclass TinyContainer {    private final Map<Class<?>, Supplier<?>> recipes = new HashMap<>();    private final Map<Class<?>, Object> singletons = new HashMap<>();
    <T> void register(Class<T> type, Supplier<T> recipe) {        recipes.put(type, recipe);    }
    <T> T getBean(Class<T> type) {        Object bean = singletons.computeIfAbsent(type, t -> recipes.get(t).get());        return type.cast(bean);    }}
public class ScopeDemo {    public static void main(String[] args) {        System.out.println("Pattern: " + (AppConfig.getInstance() == AppConfig.getInstance()));
        TinyContainer appA = new TinyContainer();        TinyContainer appB = new TinyContainer();        appA.register(CartPricing.class, CartPricing::new);        appB.register(CartPricing.class, CartPricing::new);
        CartPricing a1 = appA.getBean(CartPricing.class);        CartPricing a2 = appA.getBean(CartPricing.class);        CartPricing b1 = appB.getBean(CartPricing.class);        System.out.println("Same container: " + (a1 == a2));        System.out.println("Two containers: " + (a1 == b1));    }}
Output
AppConfig created
Pattern: true
CartPricing created
CartPricing created
Same container: true
Two containers: false

What this code does

  • AppConfig enforces one instance itself, so every getInstance() call returns the same object.
  • TinyContainer keeps one CartPricing per container, like Spring's singleton scope. Two containers make two instances, and CartPricing itself stays a normal class.

A Spring singleton is an ordinary class with a public constructor. Nothing stops tests or a second container from making another one, and that is a feature: tests can build it with fakes. The prototype scope gives a new instance on every request for the bean.

Predict the output

One bean or many?

Pick what each program prints.

Round 1 of 3

What does this print?

@Service
public class PricingService { }
PricingService a = ctx.getBean(PricingService.class);
PricingService b = ctx.getBean(PricingService.class);
System.out.println(a == b);
Singleton beans are shared by every request thread, so keep them stateless or thread-safe: no per-user fields such as currentCart.

@Bean methods as factory methods

A @Bean method inside a @Configuration class is a factory method: Spring calls it once and stores what it returns as a bean.

PaymentConfig.javaJava
@Configurationpublic class PaymentConfig {    @Bean    PaymentGateway paymentGateway(@Value("${shoplite.payment.provider}") String provider) {        return switch (provider) {            case "upi" -> new UpiPaymentGateway();            case "card" -> new CardPaymentGateway();            default -> throw new IllegalStateException("Unknown provider: " + provider);        };    }}

Example 3 · A @Bean method is a factory method

BeanMethodDemo.javaJava
import java.math.BigDecimal;
interface PaymentGateway {    String charge(BigDecimal amount);}
class UpiPaymentGateway implements PaymentGateway {    public String charge(BigDecimal amount) {        return "UPI collect request for Rs. " + amount;    }}
class CardPaymentGateway implements PaymentGateway {    public String charge(BigDecimal amount) {        return "Card charged Rs. " + amount;    }}
// What a @Configuration class with a @Bean method boils down toclass PaymentConfig {    PaymentGateway paymentGateway(String provider) {        // a factory method        return switch (provider) {            case "upi" -> new UpiPaymentGateway();            case "card" -> new CardPaymentGateway();            default -> throw new IllegalStateException("Unknown provider: " + provider);        };    }}
public class BeanMethodDemo {    public static void main(String[] args) {        PaymentConfig config = new PaymentConfig();        for (String provider : new String[] {"upi", "card", "cash"}) {            try {                PaymentGateway gateway = config.paymentGateway(provider);                System.out.println(provider + " -> " + gateway.charge(new BigDecimal("1499.00")));            } catch (IllegalStateException e) {                System.out.println(provider + " -> " + e.getMessage());            }        }    }}
Output
upi -> UPI collect request for Rs. 1499.00
card -> Card charged Rs. 1499.00
cash -> Unknown provider: cash

What this code does

  • paymentGateway(provider) is what the @Bean method above does without the annotation: a factory method that picks the implementation.
  • An unknown provider throws IllegalStateException. In Spring this happens at startup, so a bad setting stops the app before any order is taken.

Use it when the class is not yours to annotate (a library class) or when choosing the implementation needs logic. The bean's name is the method name, and the method's parameters are injected like constructor parameters. In a @Configuration class, one @Bean method calling another still gets the same singleton.

Constructor injection as DIP applied by a framework

Constructor injection means a class receives the objects it needs as constructor parameters instead of creating them with new. With Spring, the container decides which beans to pass in.

CheckoutService depends on the PaymentGateway interface, and someone outside decides which implementation it gets. That is the dependency inversion principle (DIP) from the OOP section in action.

CheckoutService.javaJava
@Servicepublic class CheckoutService {    private final PaymentGateway payments;    private final NotificationService notifications;
    public CheckoutService(PaymentGateway payments, NotificationService notifications) {        this.payments = payments;        this.notifications = notifications;    }}

Example 4 · Constructor injection makes testing easy

FakeGatewayDemo.javaJava
import java.math.BigDecimal;import java.util.ArrayList;import java.util.List;
interface PaymentGateway {    boolean charge(String orderId, BigDecimal amount);}
interface NotificationService {    void send(String to, String message);}
// Depends only on interfaces and receives them in the constructorclass CheckoutService {    private final PaymentGateway payments;    private final NotificationService notifications;
    CheckoutService(PaymentGateway payments, NotificationService notifications) {        this.payments = payments;        this.notifications = notifications;    }
    String placeOrder(String orderId, String customer, BigDecimal total) {        if (!payments.charge(orderId, total)) {            return orderId + " FAILED";        }        notifications.send(customer, "Order " + orderId + " confirmed");        return orderId + " PLACED";    }}
// Test doubles: no network, no real moneyclass FakePaymentGateway implements PaymentGateway {    final List<String> charges = new ArrayList<>();    boolean approve = true;
    public boolean charge(String orderId, BigDecimal amount) {        charges.add(orderId + "=" + amount);        return approve;    }}
class RecordingNotifications implements NotificationService {    final List<String> sent = new ArrayList<>();
    public void send(String to, String message) {        sent.add(to + ": " + message);    }}
public class FakeGatewayDemo {    public static void main(String[] args) {        FakePaymentGateway fakePay = new FakePaymentGateway();        RecordingNotifications fakeNotify = new RecordingNotifications();        CheckoutService checkout = new CheckoutService(fakePay, fakeNotify);
        System.out.println(checkout.placeOrder("ORD-101", "riya@example.com", new BigDecimal("899.00")));        fakePay.approve = false;        System.out.println(checkout.placeOrder("ORD-102", "riya@example.com", new BigDecimal("2999.00")));
        System.out.println("Charges tried: " + fakePay.charges);        System.out.println("Messages sent: " + fakeNotify.sent);    }}
Output
ORD-101 PLACED
ORD-102 FAILED
Charges tried: [ORD-101=899.00, ORD-102=2999.00]
Messages sent: [riya@example.com: Order ORD-101 confirmed]

What this code does

  • CheckoutService knows only the two interfaces. The test passes fakes through the same constructor Spring would use.
  • The fakes record what happened, so the program checks that a declined payment sends no confirmation, with no network and no Spring.

If a class has a single constructor, Spring calls it with matching beans, with no @Autowired needed (since Spring 4.3). Because the class is still plain Java, a test can call the same constructor with fakes and no Spring at all.

Find the bug

Find the hard-wired line

Click the line that makes the class hard to test.

A test cannot replace the payment gateway. Which line is the cause?

Round 1 of 2

Hand-written wiring in main vs container wiring

A composition root is the one place where objects are created and wired together, usually main in a program without a framework.

Wiring is creating each object and passing it into the objects that need it. Without a framework, main does it; with Spring, annotations describe the same steps.

Example 5 · Hand-written wiring in main

HandWiringDemo.javaJava
import java.math.BigDecimal;
interface PaymentGateway {    boolean charge(String orderId, BigDecimal amount);}
interface NotificationService {    void send(String to, String message);}
class UpiPaymentGateway implements PaymentGateway {    public boolean charge(String orderId, BigDecimal amount) {        System.out.println("[UPI] " + orderId + " paid Rs. " + amount);        return true;    }}
class EmailNotificationService implements NotificationService {    public void send(String to, String message) {        System.out.println("[Email] to " + to + ": " + message);    }}
class CheckoutService {    private final PaymentGateway payments;    private final NotificationService notifications;
    CheckoutService(PaymentGateway payments, NotificationService notifications) {        this.payments = payments;        this.notifications = notifications;    }
    void placeOrder(String orderId, String customer, BigDecimal total) {        if (payments.charge(orderId, total)) {            notifications.send(customer, "Order " + orderId + " confirmed");        }    }}
public class HandWiringDemo {    public static void main(String[] args) {        PaymentGateway payments = new UpiPaymentGateway();                  // @Component        NotificationService notifications = new EmailNotificationService(); // @Component        CheckoutService checkout = new CheckoutService(payments, notifications); // constructor injection
        checkout.placeOrder("ORD-201", "arjun@example.com", new BigDecimal("1648.00"));        checkout.placeOrder("ORD-202", "meera@example.com", new BigDecimal("150.00"));    }}
Output
[UPI] ORD-201 paid Rs. 1648.00
[Email] to arjun@example.com: Order ORD-201 confirmed
[UPI] ORD-202 paid Rs. 150.00
[Email] to meera@example.com: Order ORD-202 confirmed

What this code does

  • The first three lines of main are the composition root; the comments show the Spring annotation that replaces each line.
  • CheckoutService is the same class in both worlds. Only who calls its constructor changes.

The mapping is direct, which is why moving between the two is easy:

  • new UpiPaymentGateway() in main → @Component (or @Service) on the class.
  • new CheckoutService(payments, notifications) → Spring calls the constructor for you.
  • Choosing between two implementations → a @Bean method, @Primary or @Qualifier("name").
  • Keeping one object and passing it everywhere → singleton scope.

Order of execution

What the container does at startup

Tap the steps in the order Spring does them.

Two beans of the same interface and no @Primary or @Qualifier stop startup with NoUniqueBeanDefinitionException (expected single matching bean but found 2).

Next step

Check your understanding

12 quick questions