Card 02/ 07

ExampleDifficulty: Intermediate1 min

Constructor Injection Example: One Constructor, No @Autowired

Spring calls a class's only constructor on its own, so the annotation adds nothing.

When a class has exactly one constructor, Spring uses it for injection automatically, without @Autowired. RideService below has one constructor that takes a RideRepository, and the container passes in the only bean that implements that interface.

InMemoryRideRepository is a component, so the container creates it first and has it ready when it builds RideService:

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); }
}

Asking the context for RideService and calling getRide("42") returns the ride from the in-memory repository:

text
Ride[42]
context.getBean(RideService.class).getRide("42"), run in a container

So in current Spring code a constructor with no annotation at all is the normal case, and @Autowired on a class's only constructor adds nothing.