🎯 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 @Repository stereotype annotations
  • Write constructor injection — the recommended approach — and understand why it beats field injection
  • Register third-party classes as beans using @Bean inside a @Configuration class
  • Understand singleton vs prototype scope and when to switch
  • Resolve ambiguity between multiple beans of the same type with @Qualifier
  • Explain the difference between BeanFactory and ApplicationContext
💼 Interview reality: "What is the difference between @Component and @Service?" and "Why is constructor injection preferred?" are asked in every Spring interview. Knowing the container lifecycle and circular dependency pitfalls separates mid from senior engineers.

🌍 Real-world scenario

🌍
NairaSwift (Lagos, Nigeria)
Wiring the payment pipeline without new

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.

mvn spring-boot:run
TransferService.java + FxRateClient.java + TransferRepository.javaLesson 21 · @Service, @Component, @Repository
verified output — server started with DI wired
. ____ _ __ _ _ /\\ / ___'_ __ _ _(_)_ __ __ _ \ \ \ \ ( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \ \\/ ___)| |_)| | | | | || (_| | ) ) ) ) ' |____| .__|_| |_|_| |_\__, | / / / / =========|_|==============|___/=/_/_/_/ :: Spring Boot :: (v3.3.5) Started NairaswiftApplication in 0.851 seconds

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.

curl -s http://localhost:8765/api/hello
AppConfig.javaLesson 21 · @Configuration, @Bean, @Qualifier
verified output
{ "time": "2026-04-26T20:37:37.897383", "status": "UP", "message": "Hello from NairaSwift!" }

🔭 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.

curl -s -u samuel:pass123 http://localhost:8765/api/transfers
TransferAuditLog.java + TransferContext.javaLesson 21 · singleton vs prototype scope
verified output — transfers list endpoint, DI in action
[ { "id": 1001, "fromAccount": "NS-100001", "toAccount": "NS-100002", "amountNgn": 25000.0, "currency": "NGN", "status": "COMPLETED", "createdAt": "2026-04-26T18:37:23.205336" }, { "id": 1002, "fromAccount": "NS-100003", "toAccount": "NS-100004", "amountNgn": 150000.0, "currency": "NGN", "status": "COMPLETED", "createdAt": "2026-04-26T20:07:23.205359" } ]

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

ScopeAnnotationInstance createdUse case
Singleton@Scope("singleton") (default)Once per ApplicationContextStateless services, repositories
Prototype@Scope("prototype")Each time bean is requestedStateful helpers, request contexts
Request@Scope("request")Once per HTTP requestWeb: per-request state
Session@Scope("session")Once per HTTP sessionWeb: user session data

🎤 Interview Q&A

EasyWhat is the difference between @Component, @Service, and @Repository?
+

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.

EasyCan you have multiple constructors in a Spring bean class?
+

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).

MediumWhat is circular dependency and how do you fix it?
+

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.

MediumHow does @Qualifier work with @Autowired?
+

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.

HardWhat is the difference between BeanFactory and ApplicationContext?
+

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

Question 1 of 5
Which annotation marks a class as a Spring service bean?
Question 2 of 5
Which injection style is recommended by the Spring team?
Question 3 of 5
What is the default bean scope in Spring?
Question 4 of 5
What does @Configuration do?
Question 5 of 5
When would you use @Bean instead of @Component/@Service?
0
/ 5
Quiz complete!

Next: Request Validation and DTOs →

⚠️ Common mistakes

Field injection with @Autowired
Works but hides dependencies, prevents final fields, and requires a running Spring context for unit tests. Use constructor injection — it's explicit, testable, and the Spring team's official recommendation.
Expecting prototype scope by default
All @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.
Creating beans with new inside Spring code
new TransferService() bypasses Spring; the returned object has no injected dependencies and is not proxied for AOP/transactions. Always let Spring create managed beans.
@Bean method calling another @Bean method in a plain @Component
In a @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
Africa & India's Best AI Academy
🤖 AI-first 🎓 Placement Assistance

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 →