🎯 What you will learn
Dependency Injection (DI) is the core of Spring — objects declare what they need, the container provides it. No more manual new, no more hidden coupling. By the end of this lesson you will:
- Distinguish
@Component,@Service, and@Repositorystereotype annotations - Write constructor injection — the recommended approach — and understand why it beats field injection
- Register third-party classes as beans using
@Beaninside a@Configurationclass - Understand singleton vs prototype scope and when to switch
- Resolve ambiguity between multiple beans of the same type with
@Qualifier - Explain the difference between
BeanFactoryandApplicationContext
🌍 Real-world scenario
Samuel's TransferController must call TransferService which calls FxRateClient which calls an external API. Without DI, each class would new its collaborators, making tests impossible. With Spring's container Samuel declares what he needs — Spring provides it.
🏷️ Block 1 — Stereotype annotations
Spring scans the classpath for classes annotated with @Component or its specialisations and registers them as managed beans. Constructor injection keeps fields final and makes dependencies explicit.
Why constructor injection? Final fields cannot be reassigned; the object is always valid after construction. Unit tests can inject mocks directly via the constructor without a Spring context — no @SpringBootTest needed for pure unit tests.
⚙️ Block 2 — @Bean factory methods + @Configuration
You cannot annotate third-party classes you don't own. Use @Bean factory methods inside a @Configuration class to register any object as a managed bean.
🔭 Block 3 — Singleton vs prototype scope
By default every Spring bean is a singleton — one shared instance per ApplicationContext. Use @Scope("prototype") when you need a fresh instance every time the bean is injected.
Singleton caution: Singleton beans are shared across all requests. Never store request-specific state (user ID, trace ID) in a singleton field — use local variables or prototype-scoped beans instead.
📋 Bean scope comparison
| Scope | Annotation | Instance created | Use case |
|---|---|---|---|
| Singleton | @Scope("singleton") (default) | Once per ApplicationContext | Stateless services, repositories |
| Prototype | @Scope("prototype") | Each time bean is requested | Stateful helpers, request contexts |
| Request | @Scope("request") | Once per HTTP request | Web: per-request state |
| Session | @Scope("session") | Once per HTTP session | Web: user session data |
🎤 Interview Q&A
All three are @Component specialisations and trigger Spring bean registration. @Service semantically marks business logic; @Repository adds persistence exception translation (Spring converts SQL exceptions to DataAccessException); @Component is the generic fallback for anything that doesn't fit the other two.
Yes, but if there are multiple constructors Spring needs a hint. Annotate the preferred one with @Autowired, or use a single constructor (Spring infers it without @Autowired since Spring 4.3).
Bean A requires Bean B, which requires Bean A. Spring cannot resolve the creation order and throws BeanCurrentlyInCreationException. Fix: refactor one class to remove the cycle (preferred), or use setter/field injection for one side (lazy resolution), or introduce an event-based design with ApplicationEventPublisher.
When multiple beans of the same type exist, Spring can't choose automatically and throws NoUniqueBeanDefinitionException. @Qualifier("liveRateClient") on the injection point tells Spring exactly which bean by name to inject. Alternatively, mark one bean as @Primary to make it the default.
BeanFactory is the core DI container: lazy bean instantiation, basic DI. ApplicationContext extends it with eager singleton instantiation at startup, i18n message resolution, event publishing, AOP auto-proxying, and environment abstraction. @SpringBootApplication uses AnnotationConfigServletWebServerApplicationContext, a web-aware subclass.
📝 Quiz — 5 questions
Next: Request Validation and DTOs →
⚠️ Common mistakes
@Service/@Component beans are singletons. If you store request state in them, multiple concurrent requests will corrupt each other. Use @Scope("prototype") or store state in local variables.new TransferService() bypasses Spring; the returned object has no injected dependencies and is not proxied for AOP/transactions. Always let Spring create managed beans.@Configuration class, calling fxRateClient() from another @Bean method works because Spring proxies @Configuration classes. In a plain @Component this creates a new unmanaged instance — a subtle but critical difference.✅ Key takeaways
- @Service, @Component, @Repository register beans; Spring wires them automatically
- Constructor injection: final fields, explicit dependencies, unit-test friendly
- @Bean in @Configuration registers third-party classes as managed beans
- Default scope is singleton — share state carefully
- Spring ApplicationContext = BeanFactory + events + i18n + web support
From DI concepts to production-wired services
Join the Best AI Programs — three 5-month courses, fully online, with placement assistance. Week 1 is free.
Explore our AI-era courses →