Skip to lesson

Patterns in the JDK and Spring practice

A review of this module. Skip it if you feel confident; the next module does not need it.

Fix the mistakes

The slips that cost marks in this module. Spot each one, then check the fix.

Before the project, check that you can name the pattern behind a JDK or Spring API and spot the two classic bugs: the shared iterator cursor and the self-called @Transactional method.

Name the pattern behind an API

Ask what the API lets you change or wrap. A rule you pass in is a Strategy; a step you pass in is a template callback; a stand-in object is a Proxy or Decorator; a list of handlers is a Chain.

Example 1 · Six JDK patterns in one small program

JdkPatternTourDemo.javaJava
import java.io.BufferedReader;import java.io.ByteArrayInputStream;import java.io.IOException;import java.io.InputStream;import java.io.InputStreamReader;import java.nio.charset.StandardCharsets;import java.util.ArrayList;import java.util.Collections;import java.util.Comparator;import java.util.Iterator;import java.util.List;
public class JdkPatternTourDemo {    public static void main(String[] args) throws IOException {        byte[] csv = "Hoodie,899\nEarbuds,1499\nNotebook,60\n".getBytes(StandardCharsets.UTF_8);
        InputStream bytes = new ByteArrayInputStream(csv);        InputStreamReader chars = new InputStreamReader(bytes, StandardCharsets.UTF_8);        List<String> lines = new ArrayList<>();        try (BufferedReader reader = new BufferedReader(chars)) {                       // Decorator: adds readLine            String line;            while ((line = reader.readLine()) != null) {                lines.add(line);            }        }
        lines.sort(Comparator.comparingInt(l -> Integer.parseInt(l.split(",")[1])));    // Strategy        List<String> view = Collections.unmodifiableList(lines);
        Iterator<String> it = view.iterator();                                          // Iterator        while (it.hasNext()) {            System.out.println(it.next());        }        try {            view.add("Pen set,150");        } catch (UnsupportedOperationException e) {            System.out.println("view.add refused: the view guards the real list");        }        System.out.println("Builder: " + new StringBuilder("items=").append(view.size()));    }}
Output
Notebook,60
Hoodie,899
Earbuds,1499
view.add refused: the view guards the real list
Builder: items=3

What this code does

  • InputStreamReader adapts bytes to characters (Adapter); BufferedReader adds readLine to any reader (Decorator); the Comparator is the sort rule (Strategy).
  • Collections.unmodifiableList returns a guarding view of the same list (Proxy-like); its iterator is the Iterator pattern, and StringBuilder is a Builder.

Ten common examples, each a one-line answer you can give in an interview:

  • Iterable/Iterator and for-each → Iterator. Comparator passed to sort → Strategy.
  • StringBuilder, HttpRequest.newBuilder() → Builder. List.of, Integer.valueOf, BeanFactory, @Bean methods → Factory.
  • JdbcTemplate, RestClient → Template Method by callback. @Transactional, @Cacheable, Collections.unmodifiableList → Proxy.
  • BufferedReader → Decorator. InputStreamReader → Adapter. Servlet filters and SecurityFilterChain → Chain of Responsibility.

Predict the output

Name the pattern

Pick the pattern behind each API.

Round 1 of 3

Which pattern is new BufferedReader(new FileReader(file))?

BufferedReader in = new BufferedReader(new FileReader("orders.csv"));
String first = in.readLine();

Mistake: an Iterable that returns itself

A class that is its own iterator (iterator() returns this) shares one cursor between all loops. The first for-each works; every later loop sees nothing.

Example 2 · Bug: one shared cursor for every loop

SharedCursorBugDemo.javaJava
import java.util.Iterator;import java.util.List;
// Bug: the Iterable returns itself as the iterator, so all loops share one cursorclass BuggyCart implements Iterable<String>, Iterator<String> {    private final List<String> items;    private int index = 0;
    BuggyCart(List<String> items) {        this.items = items;    }
    public Iterator<String> iterator() {        return this;    }
    public boolean hasNext() {        return index < items.size();    }
    public String next() {        return items.get(index++);    }}
// Fix: a fresh iterator with its own position on every callclass Cart implements Iterable<String> {    private final List<String> items;
    Cart(List<String> items) {        this.items = items;    }
    public Iterator<String> iterator() {        return new Iterator<>() {            private int index = 0;
            public boolean hasNext() {                return index < items.size();            }
            public String next() {                return items.get(index++);            }        };    }}
public class SharedCursorBugDemo {    static int count(Iterable<String> cart) {        int n = 0;        for (String item : cart) {            n++;        }        return n;    }
    public static void main(String[] args) {        List<String> items = List.of("Earbuds", "Notebook", "Hoodie");
        BuggyCart buggy = new BuggyCart(items);        System.out.println("Buggy: first loop " + count(buggy) + ", second loop " + count(buggy));
        Cart fixed = new Cart(items);        System.out.println("Fixed: first loop " + count(fixed) + ", second loop " + count(fixed));    }}
Output
Buggy: first loop 3, second loop 0
Fixed: first loop 3, second loop 3

What this code does

  • BuggyCart.iterator() returns this, so the second loop starts where the first ended and counts 0 items.
  • Cart.iterator() creates a fresh anonymous iterator each time, so every loop sees all 3 items.

The fix is the rule from the Iterator lesson: iterator() returns a new iterator object each time, with its own position. The same care applies to comparators: call reversed() on the part you want reversed, before adding thenComparing.

Find the bug

Find the mistake

Click the line with the mistake.

The second loop over the cart prints nothing. Which line is wrong?

Round 1 of 2

Mistake: @Transactional on a self-called method

A call written as placeOrder(o) inside the same bean is really this.placeOrder(o). It never passes through Spring's proxy, so @Transactional on placeOrder does nothing for that call, with no warning.

Example 3 · Bug: placeAll calls placeOrder on this

Runs in: a Spring Boot project

OrderService.javaJava
package com.shoplite.order;
import java.util.List;import org.springframework.stereotype.Service;import org.springframework.transaction.annotation.Transactional;import org.springframework.transaction.support.TransactionSynchronizationManager;
@Servicepublic class OrderService {    private final OrderRepository orders;
    public OrderService(OrderRepository orders) {        this.orders = orders;    }
    public void placeAll(List<Order> batch) {        for (Order o : batch) {            placeOrder(o);                      // BUG: same as this.placeOrder(o), skips the proxy        }    }
    @Transactional    public void placeOrder(Order order) {        System.out.println(order.id() + " in transaction: "                + TransactionSynchronizationManager.isActualTransactionActive());        orders.save(order);    }}
Sample output
ORD-1 in transaction: false
ORD-2 in transaction: false

What this code does

  • placeAll has no annotation and calls placeOrder on the same object, so each order is saved without a transaction.
  • Fix: move placeAll into a BatchOrderService that receives OrderService by constructor injection; each call then goes through the proxy and prints true.

To find it, look for a public method without the annotation that calls an annotated method of the same class. To fix it, move the caller (or the annotated method) to another bean so the call goes through the injected proxy.

Predict the output

Is there a transaction?

Pick what happens to the transaction.

Round 1 of 2

Is each order saved inside a transaction?

@Service
public class OrderService {
@Transactional
public void placeOrder(Order o) { orders.save(o); }
public void placeAll(List<Order> batch) {
batch.forEach(this::placeOrder);
}
}

Reading a filter chain and predicting the path

To predict a request's path, walk the filters in order and stop at the first one that answers. The order in the configuration is the order of checks, and in authorizeHttpRequests the first matching rule decides.

Example 4 · Tracing requests through a filter chain

FilterPathDemo.javaJava
import java.util.ArrayList;import java.util.List;import java.util.function.ToIntFunction;
record Request(String method, String path, String token) { }
interface Filter {    String name();    // returns a status to stop with, or 0 to pass on    int check(Request req);}
public class FilterPathDemo {    static void walk(Request req, List<Filter> chain) {        List<String> visited = new ArrayList<>();        int status = 200;        for (Filter f : chain) {            visited.add(f.name());            int result = f.check(req);            if (result != 0) {                status = result;                break;            }        }        String end = status == 200 ? " -> controller" : "";        System.out.println(req.method() + " " + req.path() + ": " + String.join(" > ", visited) + end + " = " + status);    }
    static Filter filter(String name, ToIntFunction<Request> rule) {        return new Filter() {            public String name() { return name; }            public int check(Request req) { return rule.applyAsInt(req); }        };    }
    public static void main(String[] args) {        List<Filter> chain = List.of(                filter("Cors", r -> 0),                filter("BearerToken", r -> r.token() != null && r.token().equals("expired") ? 401 : 0),                filter("Authorization", r -> {                    boolean publicRead = r.method().equals("GET") && r.path().startsWith("/api/v1/products");                    if (publicRead) return 0;                    if (r.token() == null) return 401;                    return r.path().startsWith("/api/v1/admin") ? 403 : 0;                }));
        walk(new Request("GET", "/api/v1/products", null), chain);        walk(new Request("GET", "/api/v1/me/orders", "expired"), chain);        walk(new Request("GET", "/api/v1/me/orders", null), chain);        walk(new Request("DELETE", "/api/v1/admin/products/7", "t-riya"), chain);        walk(new Request("GET", "/api/v1/me/orders", "t-riya"), chain);    }}
Output
GET /api/v1/products: Cors > BearerToken > Authorization -> controller = 200
GET /api/v1/me/orders: Cors > BearerToken = 401
GET /api/v1/me/orders: Cors > BearerToken > Authorization = 401
DELETE /api/v1/admin/products/7: Cors > BearerToken > Authorization = 403
GET /api/v1/me/orders: Cors > BearerToken > Authorization -> controller = 200

What this code does

  • Each request walks Cors, BearerToken and Authorization in order, and the trace stops at the first filter that returns a status.
  • The expired token stops at BearerToken with 401; the customer on an admin URL passes the token check and stops at Authorization with 403.

Note which filter stopped the request and with which status: 401 from the token or authorization step for a missing or bad token, 403 for a signed-in user without the right role, 200 when every filter passes it on to the controller.

Predict the output

Trace the request

Walk the filters and pick the result.

Round 1 of 2

Which status comes back?

// filters: Cors > BearerToken > Authorization
// rule: /api/v1/admin/** needs ADMIN
DELETE /api/v1/admin/products/7 (valid token, role CUSTOMER)

Finish up

Mark complete & continue

Next: Project: a mini dependency-injection container