Skip to lesson

Practice: why Spring

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.

Every idea in this module comes back to one question: who creates the objects a class needs? Answer it for any piece of code, and you know how easy it is to change and test.

Refactoring a coupled class, step by step

Example 1 refactors a receipt class that makes its own sender and its own counter inside a method. Look for each new of a collaborator.

Example 1 · Refactor: receipts with a shared counter and an injected sender

FeeReceiptRefactorDemo.javaJava
import java.math.BigDecimal;import java.util.ArrayList;import java.util.List;
interface MessageSender {    void send(String phone, String text);}
class SmsSender implements MessageSender {    public void send(String phone, String text) {        System.out.println("  SMS to " + phone + ": " + text);    }}
class RecordingSender implements MessageSender {    final List<String> texts = new ArrayList<>();
    public void send(String phone, String text) {        texts.add(text);    }}
interface ReceiptNumbers {    String next();}
class SequentialReceiptNumbers implements ReceiptNumbers {    private int next = 1;
    public String next() {        return String.format("RCPT-%03d", next++);    }}
// Before: both helpers are created inside the methodclass OldFeeReceiptService {    void receive(String student, String phone, BigDecimal amount) {        SequentialReceiptNumbers numbers = new SequentialReceiptNumbers();        new SmsSender().send(phone, numbers.next() + ": Rs " + amount + " received from " + student);    }}
// After: both helpers come in through the constructorclass FeeReceiptService {    private final ReceiptNumbers numbers;    private final MessageSender sender;
    FeeReceiptService(ReceiptNumbers numbers, MessageSender sender) {        this.numbers = numbers;        this.sender = sender;    }
    void receive(String student, String phone, BigDecimal amount) {        sender.send(phone, numbers.next() + ": Rs " + amount + " received from " + student);    }}
public class FeeReceiptRefactorDemo {    public static void main(String[] args) {        System.out.println("Before (a new counter every call):");        OldFeeReceiptService old = new OldFeeReceiptService();        old.receive("Asha", "98450 12345", new BigDecimal("45000.00"));        old.receive("Ravi", "98860 11223", new BigDecimal("45000.00"));
        System.out.println("After (one shared counter, injected):");        FeeReceiptService service = new FeeReceiptService(new SequentialReceiptNumbers(), new SmsSender());        service.receive("Asha", "98450 12345", new BigDecimal("45000.00"));        service.receive("Ravi", "98860 11223", new BigDecimal("45000.00"));
        RecordingSender recorder = new RecordingSender();        new FeeReceiptService(new SequentialReceiptNumbers(), recorder)                .receive("Test", "00000 00000", new BigDecimal("1.00"));        System.out.println("Test recorded: " + recorder.texts);    }}
Output
Before (a new counter every call):
  SMS to 98450 12345: RCPT-001: Rs 45000.00 received from Asha
  SMS to 98860 11223: RCPT-001: Rs 45000.00 received from Ravi
After (one shared counter, injected):
  SMS to 98450 12345: RCPT-001: Rs 45000.00 received from Asha
  SMS to 98860 11223: RCPT-002: Rs 45000.00 received from Ravi
Test recorded: [RCPT-001: Rs 1.00 received from Test]

What this code does

  • The old service creates a new counter on each call, so both students get RCPT-001. The injected counter is created once in main and shared, so the second receipt is RCPT-002.
  • The injected sender lets the last lines use a RecordingSender: nothing is sent, and the check reads exactly what would have been sent.

A refactor changes how code is built without changing what it does. A coupled class always takes the same steps: find each new of a helper inside the class, give the helper an interface if it has none, add a private final field, take it through the constructor, and fix every caller. Review: Tight coupling and the new keyword (opens in a new tab)

Helpers created inside methods count too. A new SequentialReceiptNumbers() inside a method makes a fresh counter on every call, so every receipt gets number 001; injecting one shared counter fixes the coupling and the bug together.

Values are not dependencies. new BigDecimal("45000.00") or new ArrayList<>() inside a method is fine; senders, counters, gateways, repositories and clocks should be injected.

Spotting who creates which object

Example 2 prints a line from each constructor, so the creation order becomes visible. Read every new and ask who runs it.

Example 2 · Reading who creates what from the creation order

WhoCreatesWhatDemo.javaJava
class AuditLog {    AuditLog() {        System.out.println("  AuditLog created");    }}
class PaymentGateway {    PaymentGateway() {        System.out.println("  PaymentGateway created");    }}
class TicketRepository {    private final AuditLog log;
    TicketRepository(AuditLog log) {        this.log = log;        System.out.println("  TicketRepository created (got an AuditLog)");    }}
class BookingService {    private final TicketRepository tickets;    private final PaymentGateway payments;
    BookingService(TicketRepository tickets) {        this.tickets = tickets;        this.payments = new PaymentGateway();          // created inside: tight coupling        System.out.println("  BookingService created (got a TicketRepository)");    }}
public class WhoCreatesWhatDemo {    public static void main(String[] args) {        System.out.println("main starts wiring:");        AuditLog log = new AuditLog();        TicketRepository tickets = new TicketRepository(log);        BookingService booking = new BookingService(tickets);        System.out.println("Wiring done.");    }}
Output
main starts wiring:
  AuditLog created
  TicketRepository created (got an AuditLog)
  PaymentGateway created
  BookingService created (got a TicketRepository)
Wiring done.

What this code does

  • main creates AuditLog, TicketRepository and BookingService, and passes each into the next: good wiring in the composition root.
  • PaymentGateway created appears inside BookingService's constructor: that new is hidden coupling, so no test can replace the payment gateway. It should be a second constructor parameter.

A new in main (the composition root) is good, because that is where wiring belongs. A new of a collaborator inside a service's constructor or method is tight coupling, even when the rest of the class uses constructor injection. Spring prints nothing like Example 2 by default, but its startup failures name the bean it was creating, which you read the same way. Review: Inversion of control (opens in a new tab)

Picking Initializr settings for a new app

For every Spring Boot REST API in this course the answers are mostly fixed; only the names and the dependency list change from app to app.

Choose the smallest dependency list that lets the app start, and add starters as features arrive. The settings:

  • Fixed: Maven, Java, the newest plain Spring Boot 4.1.x, Jar, Java 17.
  • Group = your domain reversed (com.shoplite); artifact = the app's name in kebab-case (shoplite-api).
  • Package name = group plus a short name without hyphens (com.shoplite, in.edu.rvce.hostelfees).
  • Dependencies: Spring Web for a REST API; database, validation and security starters only when the module adds them.

Review: Creating a project with Spring Initializr (opens in a new tab)

Interview drill: Spring, Spring Boot and IoC in one minute

Interviewers ask these three together, often as the first Spring questions. Short, exact answers with one example each work best.

Spring is a framework built around a dependency injection container that creates and wires your objects, with modules for web, data access and transactions. Spring Boot sets Spring up for you with starters, auto-configuration, an embedded server and defaults, so an app runs with java -jar. IoC means your class does not create its own collaborators; something outside, the Spring container, creates them and injects them, usually through the constructor.

Likely follow-ups:

  • "Why not just use new?" → tight coupling: hard to swap, hard to test.
  • "Can you do DI without Spring?" → yes, wire in main; Spring automates it as the app grows.
  • "Is Boot a different framework?" → no, every Boot app is a Spring Framework app.

Module quiz

Questions from the whole module. Your first answer is your score.

Problems

Graded easy to hard, using everything from this module.

Try each one yourself first. Use the hint if you get stuck. Mark it as done when it works.

Exercise 1· Easy

Refactor AttendanceService so the alert sender is injected: add an AlertSender interface, make SmsGateway implement it, and pass it through the constructor. Check Kiran (68%, parent 98860 11223) and Divya (91%, parent 98450 22334).

Java
class SmsGateway {    void send(String phone, String text) {        System.out.println("SMS to " + phone + ": " + text);    }}
class AttendanceService {    void check(String student, String parentPhone, int percent) {        if (percent < 75) {            new SmsGateway().send(parentPhone, student + "'s attendance is " + percent + "%, below 75%");        } else {            System.out.println(student + ": attendance OK (" + percent + "%)");        }    }}
Expected output
SMS to 98860 11223: Kiran's attendance is 68%, below 75%
Divya: attendance OK (91%)

Exercise 2· Easy

Read Example 2's program. For each class, write who creates it: AuditLog, TicketRepository, PaymentGateway, BookingService. Then name the one object that should be created somewhere else.

Expected output
AuditLog: main
TicketRepository: main
PaymentGateway: BookingService's constructor
BookingService: main
Move: PaymentGateway should be created in main and passed to BookingService

Exercise 3· Medium

Wire a small shop app by hand. ProductRepository knows prices (Wireless mouse Rs 599.00, USB cable Rs 199.00), GstCalculator adds 18% GST, OrderNumberGenerator hands out order numbers from 101, and ShopOrderService needs all three. Write the composition root and order 2 wireless mice and 3 USB cables.

Expected output
Order 101: 2 x Wireless mouse = Rs 1413.64
Order 102: 3 x USB cable = Rs 704.46

Exercise 4· Medium

Choose the Initializr settings for fest-api, a REST API for the NITK college fest (domain nitk.ac.in) that will later use MySQL. Write one setting per line, and on the last line say which dependency you add now and why the others wait.

Expected output
Project: Maven
Language: Java
Spring Boot: 4.1.1
Group: in.ac.nitk
Artifact: fest-api
Package name: in.ac.nitk.fest
Packaging: Jar
Java: 17
Dependencies: Spring Web now; JDBC and MySQL Driver later, because without database settings they stop the app from starting

Exercise 5· Medium

Write checks for the refactored AttendanceService (alert only below 75%). Use a FakeAlertSender that records phone | text. Check four things and print PASS or FAIL with a name: no alert at 91%, no alert at exactly 75%, one alert at 68%, and the alert goes to the parent's phone 98860 11223.

Expected output
PASS no alert at 91%
PASS no alert at exactly 75%
PASS one alert at 68%
PASS alert goes to the parent

Exercise 6· Medium

Match each problem to its cause and fix, one line each: (1) package javax.servlet.http does not exist, (2) Port 8080 was already in use, (3) release version 17 not supported, (4) an endpoint returns 404 although its controller compiles.

Expected output
1. Old javax import -> change it to jakarta.servlet.http
2. Another program has port 8080 -> stop it or set server.port
3. Maven uses a JDK older than 17 -> install JDK 17+ and set JAVA_HOME
4. Controller outside com.shoplite -> move it into a package under the main class

Exercise 7· Hard

LibraryFineService charges Rs 2.00 per day late, but it calls LocalDate.now(), so its result changes every day and cannot be tested. Inject a java.time.Clock instead and use LocalDate.now(clock). With a clock fixed at 2026-10-16 in Asia/Kolkata, print the fine for due dates 2026-10-20, 2026-10-16 and 2026-10-06.

Java
class LibraryFineService {    private static final BigDecimal FINE_PER_DAY = new BigDecimal("2.00");
    BigDecimal fineFor(LocalDate dueDate) {        LocalDate today = LocalDate.now();          // hidden dependency: the system clock        long daysLate = ChronoUnit.DAYS.between(dueDate, today);        if (daysLate <= 0) {            return BigDecimal.ZERO;        }        return FINE_PER_DAY.multiply(BigDecimal.valueOf(daysLate));    }}
Expected output
Due 2026-10-20: Rs 0
Due 2026-10-16: Rs 0
Due 2026-10-06: Rs 20.00

Exercise 8· Hard

These two services need each other in their constructors, so main cannot create either one first. Redesign: InvoiceService should not need OrderService at all. Give it the data it needs instead, as an Order record (id, customer, total). Place order 901 for Asha with total Rs 2598.00.

Java
class OrderService {    private final InvoiceService invoices;
    OrderService(InvoiceService invoices) {        this.invoices = invoices;    }
    BigDecimal totalOf(int orderId) {        return new BigDecimal("2598.00");    }
    void placeOrder(int orderId, String customer) {        System.out.println("Order " + orderId + " placed");        System.out.println(invoices.invoiceFor(orderId, customer));    }}
class InvoiceService {    private final OrderService orders;
    InvoiceService(OrderService orders) {        this.orders = orders;    }
    String invoiceFor(int orderId, String customer) {        return "Invoice for order " + orderId + " (" + customer + "): Rs " + orders.totalOf(orderId);    }}
// main: new OrderService(new InvoiceService(???)) -- which comes first?
Expected output
Order 901 placed
Invoice for order 901 (Asha): Rs 2598.00

Interview questions

Questions interviewers ask on this topic.

Finish up

Mark complete & continue

Next: Mini project: ShopLite API skeleton