Spring Boot Template Method Pattern Example

By Ercan - 19/10/2025 - 0 comments

Design patterns are timeless tools that bring structure and clarity to software projects. In this post, we’ll explore how to use the Template Method Pattern within a Spring Boot application — through a simple but practical example: an Email Builder API.

TL;DR: If you want to skip the explanation and dive straight into the code, check out the full implementation on GitHub: https://github.com/ercansormaz/template-method-pattern


What Is the Template Method Pattern?

The Template Method Pattern defines the skeleton of an algorithm in a base (abstract) class and allows subclasses to redefine certain steps without changing the algorithm’s structure.

In short:

  • The abstract class defines the template method (often final to prevent overriding).
  • The subclasses customize specific steps of the process.

This ensures consistency while allowing flexibility where it’s needed.


Project Overview

In this example, we’re building a REST API that generates email content dynamically.
Each email has three main parts:

  • Header
  • Body
  • Footer

The body is provided via the API request, while the header and footer depend on the email’s category — for example: family, friend, or work.


How It Works

Here’s a simplified example request and response:

Request

curl --location 'http://localhost:8080/email/build' \
--header 'Content-Type: application/json' \
--data '{
  "category": "work",
  "body": "Test email body"
}'

Response

{
  "content": "Dear Colleague,\n\nTest email body\n\nBest regards, Your Company"
}

🧱 Class Structure

The application’s class design is clean and extensible:

Layer Class Description
template EmailTemplate (abstract) Defines the template method buildEmail() as final. Subclasses must implement getHeader() and getFooter().
template.impl WorkEmailTemplate, FamilyEmailTemplate, FriendEmailTemplate Concrete implementations defining unique headers and footers.
service EmailService Selects the right template using Spring’s dependency injection and builds the email.
controller EmailController Exposes the /email/build REST endpoint.

 


Template Method in Action

The abstract class defines the final method buildEmail() which cannot be overridden.
This guarantees the algorithm’s structure remains consistent:

public abstract class EmailTemplate {

    public final String buildEmail(String body) {
        return getHeader() + "\n\n" + body + "\n\n" + getFooter();
    }

    protected abstract String getHeader();
    protected abstract String getFooter();
}

Each subclass defines its own style:

@Component("work")
public class WorkEmailTemplate extends EmailTemplate {

    @Override
    protected String getHeader() {
        return "Dear Colleague,";
    }

    @Override
    protected String getFooter() {
        return "Best regards, Your Company";
    }
}

Dependency Injection Makes It Flexible

Thanks to Spring’s DI, EmailService automatically maps each EmailTemplate by its component name (work, friend, family) and uses it dynamically based on the incoming category:

@Service
@RequiredArgsConstructor
public class EmailService {

    private final Map<String, EmailTemplate> templates;

    public String buildEmail(String category, String body) {
        EmailTemplate template = templates.get(category);
        if (template == null) {
            throw new EmailCategoryNotFoundException("Unknown category: " + category);
        }
        return template.buildEmail(body);
    }
}

Why the Template Method Pattern Fits Perfectly

This pattern works great here because:

  • You want a consistent email structure (header, body, footer).
  • Each category has different behavior but the same algorithm flow.
  • You can easily add new email types without touching existing logic.

Benefits of This Approach

  • Promotes code reuse and consistency
  • Keeps the algorithm flow protected (final template method)
  • Makes the system open for extension, closed for modification
  • Integrates naturally with Spring Boot’s DI container

Final Thoughts

The Template Method Pattern is an elegant solution for defining fixed workflows with customizable steps.
By combining it with Spring Boot’s dependency injection, you can build clean, extensible systems — just like this Email Builder API.

👉 You can explore the full source code on GitHub:
https://github.com/ercansormaz/template-method-pattern

Tags: spring boot, design pattern, template method pattern, java