Card 02/ 07

ExampleDifficulty: Intermediate1 min

One Constructor, No @Autowired Needed

RideService, rewritten with the one constructor it actually needs — and no @Autowired anywhere on it.

java
package rides;

interface RideRepository { String findById(String id); }

@Component
class InMemoryRideRepository implements RideRepository {
    public String findById(String id) { return "Ride[" + id + "]"; }
}

@Service
class RideService {
    private final RideRepository repository;

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

    String getRide(String id) { return repository.findById(id); }
}
text
Ride[42]
context.getBean(RideService.class).getRide("42") — run in a container