The Analogy: A Theatre's Props Store
Backstage at a repertory theatre sits the props store, run by a props master. No actor makes their own props. When a scene is being set up, its requirements are read off a list -- this scene needs the silver candlestick, the sealed letter, and the duelling pistol -- and the props master issues exactly those items from the store. The actors declare what they need and receive it; they never disappear into a workshop to fabricate a candlestick mid-performance. That separation is the whole point: the people performing a scene should not also be sourcing its equipment.
This is dependency injection, and the Spring container is the props master. A bean is any object the container creates, wires, and manages -- the candlestick, the letter, the pistol. A class states its needs in its constructor, the way a scene lists its props, and the container supplies them. Contrast the alternative, where a scene builds its own pistol on stage: a class that writes new StripePaymentClient() inside itself is welded to that exact prop, and you can no longer rehearse the scene with a harmless wooden stand-in. Inject the dependency instead and a test can hand the scene a fake pistol, while swapping the real supplier is a change to the store's inventory, not to the script.
The store issues props under two policies, and choosing the wrong one causes real trouble. The default policy is one shared item: a single candlestick lives in the store and every scene that needs a candlestick gets that same object. This is the singleton scope, and it is efficient precisely because there is one instance for the whole production. The other policy is a fresh item every time it is asked for -- the prototype scope -- used when each scene must have its own, because sharing would be wrong. The shared-item default is why a singleton bean must be stateless: if one scene scribbles a note on the shared letter, every later scene inherits the scribble, which under concurrent performances is a data race waiting to corrupt someone else's show.
Two failures come straight from the store. The first is the deadlock of mutual dependence: scene A cannot be set up until it has the prop from scene B, and scene B cannot be set up until it has the prop from scene A, so neither is ever ready and the curtain never rises. That is a circular constructor dependency, and the container detects it and refuses to start rather than hang forever. The second is ambiguity: a scene asks for "a pistol" and the store holds two different pistols with no indication of which is meant. The props master will not guess -- it stops and demands you either mark one as the default or name the exact one you want.
Syntax or Core Structure
A class declares its dependencies as constructor parameters, and the container supplies them. A single-constructor class needs no annotation to mark the injection point -- Spring infers it. The dependencies must be built before the class that needs them, so the container works out a creation order by resolving each bean's prerequisites first.
@Service
public class OrderService {
private final PaymentClient payments;
private final OrderRepository orders;
public OrderService(PaymentClient payments, OrderRepository orders) {
this.payments = payments; // fields can be final: genuinely immutable
this.orders = orders;
}
}
Given a small graph of beans, the container creates each one only after everything it depends on already exists, then wires the dependents. Tracing the order for a controller that needs a service, which in turn needs a client and a repository, shows the dependencies-first rule:
Output:
bean depends on
------------------------------------
OrderController OrderService
OrderService PaymentClient, OrderRepository
PaymentClient (none)
OrderRepository (none)
------------------------------------
creation order : PaymentClient OrderRepository OrderService OrderController
cycle detected : no
The two leaf beans with no dependencies are created first, then OrderService (which needed them), and finally OrderController at the top. Because every bean's prerequisites exist before it is built, no object is ever half-initialised -- which is the deep reason to prefer constructor injection over setting fields after construction. The absence of a cycle is what makes an ordering possible at all; when one exists, no valid order does, and startup fails.
Technical Depth: Registration, Scope, and Ambiguity
Registering beans
You register a class you own with a stereotype annotation, and a type you do not own with a @Bean factory method inside a @Configuration class. The stereotypes are near-identical in behaviour; the distinction communicates intent to a reader.
| Annotation | Intent |
|---|---|
| @Component | Generic managed component |
| @Service | Business logic |
| @Repository | Data access, adds exception translation |
| @RestController | HTTP endpoint |
You cannot annotate a library class such as an HTTP client, so a factory method registers it:
@Configuration
public class HttpConfig {
@Bean
RestClient restClient() {
return RestClient.builder().baseUrl("https://api.example.com").build();
}
}
Scope: one shared instance, or one each
By default a bean is a singleton -- a single instance shared across the whole application, no matter how many other beans inject it. A prototype-scoped bean is created afresh at each injection point or lookup. The difference is stark when several beans depend on the same type.
@Service // singleton by default: one instance
public class PricingService { }
@Component
@Scope("prototype") // a new instance every time it is requested
public class RequestScratchpad { }
Output:
scope injection points instances
----------------------------------------
singleton 3 1
prototype 3 3
----------------------------------------
singleton must be : stateless
Three beans inject the type; as a singleton that is one shared instance, as a prototype it is three separate ones. The shared-instance default carries an obligation: a singleton must be stateless, because a mutable field on it is shared by every concurrent request and becomes a data race. Keep per-request data in method parameters and locals, never in singleton fields.
Resolving ambiguity
When one interface has two implementations, an injection point that asks for the interface is ambiguous, and the container refuses to guess. You resolve it by marking one implementation @Primary (the default choice) or by naming the exact bean at the injection point with @Qualifier.
@Service @Primary
public class StripePaymentClient implements PaymentClient { }
@Service
public class PaypalPaymentClient implements PaymentClient { }
Output:
injection point candidates resolves to
---------------------------------------------------
PaymentClient 2 StripePaymentClient (primary)
@Qualifier paypal... 2 PaypalPaymentClient
PaymentClient no prim 2 AMBIGUOUS startup fails
---------------------------------------------------
unresolved without hint : 1
A plain request for PaymentClient resolves to the @Primary bean; a @Qualifier overrides that and selects the named one. The third row is the failure: two candidates, no @Primary, and no qualifier means the container cannot choose, and startup aborts with a no-unique-bean error. The fix is always to add exactly one hint -- a primary for the common default, a qualifier for the exception.
Real World Example: A Circular Dependency at Startup
A notifications feature grows organically. EmailService needs TemplateService to render message bodies, so it takes it in its constructor. Later, someone adds a feature where TemplateService needs to send a preview email, so they inject EmailService into TemplateService. Each change is reasonable on its own. Together they form a loop: neither service can be constructed until the other exists. A NotificationSvc that depends on both sits on top, and the application refuses to start. This program models what the container computes.
@Service
public class EmailService {
public EmailService(TemplateService templates) { } // needs Template
}
@Service
public class TemplateService {
public TemplateService(EmailService email) { } // needs Email -- loop!
}
@Service
public class NotificationSvc {
public NotificationSvc(EmailService e, TemplateService t) { }
}
Output:
bean constructor needs
----------------------------------------
NotificationSvc EmailService, TemplateService
EmailService TemplateService
TemplateService EmailService
----------------------------------------
cycle : EmailService <-> TemplateService
creation order : none
startup : FAILED
reason : circular constructor dependency
The container tries to order the beans so each is built after its dependencies. EmailService waits for TemplateService, which waits for EmailService, so neither can ever be first. No valid creation order exists, so the ordering comes back empty and startup fails with a circular-dependency error naming the two beans in the loop. NotificationSvc is an innocent bystander -- it is fine in itself, but it can never be built because its two dependencies can never be built.
The error is genuinely helpful here: it names the cycle rather than hanging, because the container detected that no ordering is possible before trying to construct anything. The correct fix is to break the loop, usually by extracting the shared behaviour into a third bean that both depend on, so the graph becomes acyclic. What you should not do is reach for the workaround that makes the symptom disappear without addressing the design: field or setter injection can construct both objects half-built and wire them afterwards, which lets the application start -- but it has only hidden a genuine design smell, and the two services are still knotted together in a way that will resist testing and change.
This model is a simplification with instructive limits. It treats the dependency graph as static and fully known at startup, whereas a real application can defer construction with @Lazy or with provider injection, turning a hard startup failure into a subtler runtime one that fires only when the lazy bean is first touched. It also reports a single cycle cleanly, while real graphs can contain several overlapping cycles that a terse error message summarises poorly. The real design flaw the example exposes is not in any one class but in the coupling itself: two services that each need the other are a sign the responsibilities are split along the wrong line, and every mechanism that "solves" a circular dependency without redrawing that line -- lazy proxies, setter injection, field injection -- is treating a symptom while leaving the structural problem in place for the next person to trip over.
Common Mistakes
- Constructing dependencies with
newinside a class. Writingnew StripePaymentClient()welds the class to that implementation, so it cannot be tested with a fake or reconfigured to a different provider. Declare the dependency in the constructor and let the container supply it.
- Using field injection with
@Autowired. Field injection hides dependencies from the constructor, preventsfinalfields, allows half-initialised objects, and -- most damagingly -- lets a circular dependency start successfully instead of failing loudly. Prefer constructor injection in every case.
- Putting mutable state on a singleton bean. A field on a
@Serviceis shared by every concurrent request, so a request-specific value stored there is a data race. Keep per-request data in method parameters and local variables, never in singleton fields.
- Injecting an interface with two implementations and no hint. Two candidates with no
@Primaryand no@Qualifiermake the injection point ambiguous, and startup fails with a no-unique-bean error. Mark one implementation primary or name the exact bean at the injection site.
- Solving a circular dependency with
@Lazyor field injection. These let the application start but leave the underlying coupling in place. Break the cycle by extracting the shared responsibility into a third bean; do not paper over it with a proxy.
- Expecting a prototype bean injected into a singleton to be recreated per use. A prototype injected once into a singleton is resolved once, so the singleton holds a single prototype instance for its whole life. If you need a fresh instance per call, inject a provider and ask it for one each time.
- Overusing stereotype annotations to signal behaviour.
@Service,@Component, and@Repositorybehave almost identically; only@Repositoryadds exception translation. Choosing@Servicedoes not change how the bean works -- it communicates intent, nothing more, so do not expect a functional difference.
- Registering a library type as if you could annotate it. You cannot put
@Componenton a class you do not own. Register it with a@Beanfactory method in a@Configurationclass instead.
- Adding
@Autowiredto a single-constructor class. When a class has exactly one constructor, Spring uses it for injection automatically. The extra annotation is noise, and its presence misleads readers into thinking multiple constructors exist.
Best Practices
- Use constructor injection for every dependency, so fields can be
final, objects are never half-built, and circular dependencies fail loudly at startup rather than hiding.
- Keep singleton beans stateless, holding no request-specific mutable field, and pass per-request data through method parameters and local variables.
- Resolve an ambiguous injection with exactly one hint: mark the usual choice
@Primaryand name the exception with@Qualifierat its injection point.
- Break a circular dependency by redrawing responsibilities -- extract the shared behaviour into a third bean -- rather than reaching for a lazy proxy or field injection.
- Register classes you own with the stereotype that best communicates their role, and register types you do not own with a
@Beanfactory method.
- Omit
@Autowiredon single-constructor classes and let Spring infer the injection point, keeping the code free of redundant annotations.
- When a singleton genuinely needs a fresh instance of a prototype per operation, inject a provider and request an instance each time rather than holding one.
- Depend on interfaces rather than concrete implementations at injection points, so swapping a provider or supplying a test double is a configuration change, not a code change.
Practice Exercises
- A
ReportServiceholdsprivate List<Row> currentRowsas a field, populated at the start of each request. Explain what goes wrong under concurrent load, why it is a consequence of the singleton scope, and how to fix it.
- Given four beans where a controller needs a service, the service needs a client and a repository, and the client and repository need nothing, write out the creation order the container will use and explain why it is the only valid one.
- An interface
Notifierhas two implementations and the application fails to start with a no-unique-bean error. Show two different one-line changes that fix it, and describe when you would choose each.
- Two services each take the other in their constructor and the application will not start. Explain why no creation order exists, then describe the structural fix and why using
@Lazyinstead would be the wrong choice.