Dependency Injection

Let Spring create and connect application objects instead of constructing dependencies manually.

Dependency injection means a class receives the objects it needs from outside. This keeps classes focused and makes them easier to test.

@Service
class GreetingService {
    String message() { return "Hello from Spring"; }
}

@RestController
class GreetingController {
    private final GreetingService service;

    GreetingController(GreetingService service) {
        this.service = service;
    }
}

What Spring does

  1. Scans packages for components such as @Service and @RestController.
  2. Creates managed objects called beans.
  3. Uses the constructor to provide GreetingService to the controller.
Prefer constructor injection: dependencies are visible, fields can be final, and unit tests can pass fake implementations easily.

Common stereotypes

Annotation Typical role
@Component General Spring-managed component.
@Service Business logic.
@Repository Data access.
@RestController HTTP API controller.
Next: Configuration →