Spring bootIntermediate

Creational Patterns in Spring Boot: Factory & Builder

DeveloperHat Team
13 min read

TL;DR

Factory, Builder, and Singleton in real Spring Boot code: @Bean factories, fluent builders, and why the container makes hand-rolled singletons obsolete.

Every Spring Boot application is full of creational design patterns, and most developers never notice — because the framework already implements them. The @Bean method you write in a @Configuration class is a Factory. The container that hands you a single shared service is the Singleton, done properly. The pattern you still write by hand is usually the Builder, and even there Spring has opinions about when it earns its keep.

This article covers the three creational patterns that matter in a Spring Boot codebase — Factory, Builder, and Singleton — with real code in Spring Boot 4.2 (Spring Framework 7.1, Java 17 minimum), the framework's built-in version of each pattern, and the anti-pattern to stop writing. The short version up front: let the container create things, use factories when the implementation is a runtime decision, use builders when an object has enough optional parts to confuse a constructor, and never write a Singleton yourself again.

Three patterns, one container that already knows them Factory @Bean methods decide Builder assemble, then hand over Singleton one instance, shared Spring ApplicationContext creates · wires · owns lifecycle You write the creation logic; the container decides when it runs and how long the result lives.

Factory: a @Bean method is the factory method

The Factory pattern exists for one situation: the caller needs an object, but which implementation it gets is a decision — configuration, environment, feature flag, or runtime input. In plain Java you write a factory class with an if chain. In Spring Boot you write a @Bean method, and the container becomes the factory.

@Configuration
public class PaymentConfig {

    @Bean
    @ConditionalOnProperty(name = "payments.provider", havingValue = "stripe")
    public PaymentGateway stripeGateway(StripeClient client) {
        return new StripePaymentGateway(client);
    }

    @Bean
    @ConditionalOnProperty(name = "payments.provider", havingValue = "adyen")
    public PaymentGateway adyenGateway(AdyenClient client) {
        return new AdyenPaymentGateway(client);
    }
}

The caller never sees the decision. It declares what it needs and the container supplies the right implementation:

@Service
public class CheckoutService {

    private final PaymentGateway gateway;

    public CheckoutService(PaymentGateway gateway) {
        this.gateway = gateway;
    }
}

Two details make this more than a renamed if statement. First, @Configuration classes are proxied by default, so if one @Bean method calls another, the call goes through the container and returns the managed instance rather than constructing a second copy. That proxying is what turns a configuration class into a real factory instead of a bag of new calls. Second, the conditional annotations — @ConditionalOnProperty, @ConditionalOnClass, @ConditionalOnMissingBean — move the selection logic out of your code and into declarative metadata, which is exactly where it belongs: the choice of implementation is configuration, not business logic.

When the choice has to happen at runtime rather than at startup, reach for ObjectProvider instead of injecting a single bean:

@Service
public class NotificationRouter {

    private final ObjectProvider<Notifier> notifiers;

    public NotificationRouter(ObjectProvider<Notifier> notifiers) {
        this.notifiers = notifiers;
    }

    public void route(User user, String message) {
        Notifier notifier = notifiers.stream()
                .filter(n -> n.supports(user.channel()))
                .findFirst()
                .orElseThrow(() -> new IllegalStateException("No notifier for " + user.channel()));
        notifier.send(user, message);
    }
}

ObjectProvider is the framework's built-in answer to "I need one of several beans, and I won't know which until the request arrives." It keeps the selection logic in your service while the container still owns creation.

Spring also ships a lower-level factory hook, FactoryBean, for cases where creating the object is itself complicated — a client that needs a multi-step build, a proxy, or a resource pool. You will rarely need it: a @Bean method covers the same ground with less ceremony, and FactoryBean mostly survives for framework internals and third-party integrations. If you find yourself implementing FactoryBean in application code, check first whether a @Bean method plus a Builder (below) does the job.

Builder: assemble complex objects, then hand them over

The Builder pattern is for objects with many parts, several of them optional, where a constructor would be a wall of parameters and a telescoping set of overloads. The classic example is a message, a report, or a request object:

public final class EmailMessage {

    private final String to;
    private final String subject;
    private final String body;
    private final List<String> cc;
    private final boolean trackOpens;

    private EmailMessage(Builder builder) {
        this.to = builder.to;
        this.subject = builder.subject;
        this.body = builder.body;
        this.cc = List.copyOf(builder.cc);
        this.trackOpens = builder.trackOpens;
    }

    public static Builder builder() {
        return new Builder();
    }

    public static final class Builder {
        private String to;
        private String subject;
        private String body = "";
        private List<String> cc = List.of();
        private boolean trackOpens = true;

        public Builder to(String to) { this.to = to; return this; }
        public Builder subject(String subject) { this.subject = subject; return this; }
        public Builder body(String body) { this.body = body; return this; }
        public Builder cc(List<String> cc) { this.cc = cc; return this; }
        public Builder trackOpens(boolean trackOpens) { this.trackOpens = trackOpens; return this; }

        public EmailMessage build() {
            Objects.requireNonNull(to, "to is required");
            Objects.requireNonNull(subject, "subject is required");
            return new EmailMessage(this);
        }
    }
}

Used at the call site, the intent is readable and the required fields are enforced once, in build(), instead of scattered across constructors:

EmailMessage message = EmailMessage.builder()
        .to("ops@example.com")
        .subject("Nightly deploy finished")
        .body(summary)
        .cc(List.of("release@example.com"))
        .build();

The hand-written version above is worth writing once so the mechanics are visible, but in a real codebase the framework's ecosystem has a shorter path: Lombok's @Builder generates the same structure from the fields, and for simple value objects a Java record with a compact constructor gives you immutability and validation without any builder at all. The rule of thumb: if the object has three or fewer fields, use a constructor or a record — a builder is ceremony with no payoff. If it has five or more, several optional, and an invariant to check before the object exists, a builder earns its place. Between three and five, let readability at the call site decide.

Where does the Builder meet the Factory? A @Bean method is the natural place to run a builder. The factory decides which object to create; the builder decides how it is assembled. Keep those two jobs separate and both stay simple:

@Bean
public EmailMessage welcomeMessage(TemplateService templates) {
    return EmailMessage.builder()
            .to("new-user@example.com")
            .subject("Welcome to Cleartechy")
            .body(templates.render("welcome"))
            .trackOpens(false)
            .build();
}

Singleton: the pattern Spring already implements

This is the part of the article that saves you the most future debugging. The Singleton pattern — exactly one instance of a class, reachable globally — is the creational pattern Spring Boot makes obsolete, and the hand-rolled version is the anti-pattern to stop writing.

The classic implementation looks like this:

// Anti-pattern — do not write this in a Spring Boot application
public class ConfigStore {

    private static volatile ConfigStore instance;

    private ConfigStore() { }

    public static ConfigStore getInstance() {
        if (instance == null) {
            synchronized (ConfigStore.class) {
                if (instance == null) {
                    instance = new ConfigStore();
                }
            }
        }
        return instance;
    }
}

It compiles, it works, and it costs you in four ways that only show up later. The dependency is hidden: nothing in CheckoutService's constructor says it depends on ConfigStore, so the coupling is invisible to the next reader and to every test. It is untestable in isolation: you cannot substitute a fake ConfigStore without mutating global static state, which makes tests order-dependent. It is a global: any code anywhere can reach it, so its state becomes shared mutable state across the whole application. And it duplicates what the container already guarantees — one instance, created once, with lifecycle callbacks — while doing it worse, with no scope control and no graceful shutdown.

The Spring replacement is not a pattern at all. It is a declaration:

@Service
public class ConfigStore {
    // plain class — no statics, no getInstance, no synchronization
}

@Service
public class CheckoutService {

    private final ConfigStore config;

    public CheckoutService(ConfigStore config) {
        this.config = config;
    }
}

Beans are singleton-scoped by default in Spring, which means the container creates exactly one instance per application context and injects that same instance everywhere it is requested. Constructor injection makes the dependency explicit, testable — pass a fake ConfigStore in the test constructor — and visible in the class's public surface. The lifecycle comes free: @PostConstruct for initialization, @PreDestroy for shutdown, and the container owns both.

The container, layer by layer — creation flows down, instances flow up Your code — constructor injection points, no new anywhere ApplicationContext — resolves dependencies, manages lifecycle @Configuration — @Bean factory methods are the creation logic Bean definitions — metadata: scope, dependencies, init/destroy Singleton instances — one shared object per bean, created once The hand-rolled Singleton lived at the bottom layer. The container moved it there for you.

There is exactly one legitimate reason to leave the default scope: you need a new instance per injection point or per request. That is what @Scope("prototype") is for, and it is the honest version of "don't share this one":

@Component
@Scope("prototype")
public class ReportBuilder {
    // stateful, per-use object — a fresh instance every time it is injected
}

Note the trap: injecting a prototype bean into a singleton gives you one prototype instance, created once at injection time, not a fresh one per call. If you need a new instance per method call, inject an ObjectProvider or a javax.inject.Provider and call .get() each time — the same ObjectProvider mechanism from the Factory section, doing double duty.

Head-to-head: Factory vs Builder vs Singleton

PatternThe question it answersThe Spring Boot wayWrite it by hand when…
FactoryWhich implementation do I get?@Bean method + @ConditionalOn…; ObjectProvider for runtime choiceNever for bean selection — the container is the factory
BuilderHow do I assemble this complex object?Lombok @Builder, or a hand-written builder for validated value objectsThe object has 5+ fields, several optional, with invariants to check
SingletonHow do I guarantee one shared instance?Default bean scope — declare the class, inject itNever — a hand-rolled Singleton duplicates the container, badly

The table hides one asymmetry worth stating plainly. Factory and Builder are patterns you use; Singleton, in a Spring Boot application, is a property you get from the container. The moment you write getInstance() you have taken on a job the framework already does, and you have paid for it with hidden coupling and untestable code.

Architecture decision: creational patterns in Spring Boot

  • Decision: Use @Bean factory methods for implementation selection, Builders for complex object assembly, and the container's default singleton scope instead of any hand-rolled Singleton. Forbid static getInstance() in application code.
  • Context: The codebase is Spring Boot 4.2 on Java 17+, with constructor injection as the team standard. New services start from this decision; existing services adopt it as files are touched.
  • Options considered: (a) Hand-written factories, builders, and singletons in plain Java, ignoring the container. (b) The container-first approach above. (c) A dedicated factory library or code generation for object creation.
  • Why this one: Option (b) removes an entire class of bugs — duplicate instances, hidden dependencies, order-dependent tests — by deleting code rather than adding it. Option (a) re-implements container features with worse lifecycle and testability. Option (c) adds a dependency for a problem @Bean methods already solve.
  • What it costs you: The team has to learn the conditional annotations and the ObjectProvider idiom, and code review has to catch new creeping into services that should be injecting. Prototype-scope injection into singletons is a known footgun that needs the ObjectProvider workaround documented.
  • When to reverse it: If a component genuinely must live outside the container — a library used by non-Spring code, a static utility with no dependencies — a plain factory or a carefully written singleton is acceptable there, isolated in the library module and never mixed into Spring-managed services. Revisit if the application ever moves off Spring, at which point the container-provided guarantees disappear with it.
  • Pick the pattern by the question, not by habit What do you need? start from the requirement Choose impl at runtime config · feature flag Build a complex object many optional fields One shared instance stateless service @Bean factory method return the right impl Builder fluent, validated Default singleton bean just declare it If none of the three questions fits, you probably need a plain constructor — not a pattern.

    Recommendation

    For a new Spring Boot service, adopt three rules and enforce them in review. First, no new in a @Service for a collaborator — if a service needs something, it declares it in the constructor and the container provides it. Second, implementation choices go in @Bean methods with conditional annotations, not in if chains inside services. Third, objects with more than a few fields get a builder — Lombok's @Builder by default, hand-written when the object needs validation at build time — and simple values stay records or constructors.

    For an existing service, the migration is incremental and safe. Replace one getInstance() call at a time: turn the class into a @Service or @Component, inject it through the constructor, and delete the static accessor. Each replacement is a small, testable change, and the test suite gets easier with every one — the fake replaces the global.

    When NOT to use these patterns

  • Don't build a factory for a single implementation. If there is only one PaymentGateway and no configuration fork, a plain @Service is the whole design. A factory with one branch is indirection with no decision behind it.
  • Don't add a builder to a three-field object. A constructor or a record is clearer, shorter, and easier to review. The builder pays off when the parameter list stops being readable.
  • Don't reach for prototype scope to fix shared mutable state. If a singleton service is accumulating per-request state in fields, the fix is to move that state into method parameters or a request-scoped bean — not to make the service prototype and hope the callers notice.
  • Don't use ObjectProvider where a plain injection works. It is for genuine runtime selection among several beans. Using it to lazily dodge a circular dependency papers over a design problem; the honest fix is to break the cycle.
  • Don't keep a hand-rolled Singleton "because it works." It works until the first test that needs a fake, the first second classloader, or the first reader who cannot see the dependency. The container's version works in all three cases, and it is already running.
  • The creational patterns are not going away — every application still has to decide what gets created, how it is assembled, and how long it lives. Spring Boot's contribution is that two of those three decisions already have a correct, tested answer built in. Your job is to use it, and to spend the patterns budget where it still matters: the factory that chooses, and the builder that assembles. For the broader question of how these choices fit into a service's overall shape, our cloud-native patterns guide covers the patterns that sit above object creation, and the API gateway patterns guide shows where factories earn their keep at the edge. If you are still deciding which Spring Boot line to build on, start with what's new in Spring Boot 4.2 — the container behavior described here is the same across the 4.x line, and 4.2 is the current default.

    Why This Matters

    Understanding the business and technical context helps you make informed decisions rather than blindly following patterns.

    Trade-offs to Consider

    Every architectural decision involves trade-offs. Consider your specific requirements, team expertise, and scale when evaluating options.

    When NOT to Use This

    Knowing when a solution doesn't apply is as valuable as knowing when it does. Consider alternatives for your specific situation.

    Decision Framework

    Use this framework to evaluate whether this approach is right for your use case based on your specific constraints and requirements.

    Share this articleShare on XShare on LinkedIn

    Keep the decision frameworks coming

    One practical architecture guide a week — patterns, trade-offs, and when not to use them. No spam, unsubscribe anytime.