Card 02/ 05

ExampleDifficulty: Beginner1 min

Constructor Injection, by Hand

The same RideService, rewritten with no Spring anywhere in sight — a constructor parameter is the entire fix.

java
interface RideRepository {
    Ride findById(String id);
}

class PostgresRideRepository implements RideRepository {
    public Ride findById(String id) { /* talks to Postgres */ return null; }
}

class FakeRideRepository implements RideRepository {
    public Ride findById(String id) { return new Ride(id); }
}

class RideService {
    private final RideRepository repository;

    RideService(RideRepository repository) {
        this.repository = repository;
    }

    Ride getRide(String id) {
        return repository.findById(id);
    }
}
java
RideService service = new RideService(new FakeRideRepository());
Ride ride = service.getRide("ride-1");
System.out.println("Got ride " + ride.id + " with no database running");
text
Got ride ride-1 with no database running
run in a container, javac 21

Nothing here needs a framework. new RideService(new FakeRideRepository()) is Dependency Injection — Spring's whole job, once it shows up, is doing this same handing-in automatically, for every bean, from what each constructor asks for.