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
-
Scans packages for components such as
@Serviceand@RestController. - Creates managed objects called beans.
-
Uses the constructor to provide
GreetingServiceto 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. |