Card 02/ 05
All 5 cards
ExampleDifficulty: Beginner1 min
Constructor Injection, by Hand
The same RideService, rewritten with no Spring anywhere in sight — a constructor parameter is the entire fix.
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);
}
}RideService service = new RideService(new FakeRideRepository());
Ride ride = service.getRide("ride-1");
System.out.println("Got ride " + ride.id + " with no database running");Got ride ride-1 with no database runningNothing 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.