Dependency Injection
Dependency injection means OrderService names a PricingClient and the container passes the bean it already manages.
Introduction
Dependency injection means OrderService names a PricingClient and the container passes the bean it already manages. The service does not call new PricingClient(). That inversion is what makes checkout rules testable.
On Spring Boot 3 / Java 21 the standard is constructor injection into final fields. One constructor is selected automatically — @Autowired has been optional since Spring Framework 4.3. A unit test passes fakes with new and never starts a context. Field injection hides the graph and cannot assign final. ObjectProvider<T> is the usual way to express an optional or lazy collaborator.
Two beans of one type fail startup with NoUniqueBeanDefinitionException. @Qualifier("promo") on the parameter is an explicit choice; @Primary is only the fallback. List<PricingClient> injects every match, which is the right shape for a fan-out.
Since Boot 2.6, circular constructors fail unless spring.main.allow-circular-references=true. Leave the flag off. Extract a third type, publish an event, or look the dependency up through ObjectProvider. A half-initialized payment bean is worse than a failed boot.
Purpose of this lesson
Wire Orders through constructors, disambiguate two pricing beans, and test place with new OrderService(fake) — reserve @SpringBootTest for HTTP and JPA.
Understanding the topic
Spring matches parameters by type, then by qualifier. Dependencies exist before your constructor runs.
- Constructor: required collaborators,
finalfields, plainnewin tests. - Several constructors: mark the one Boot should call with
@Autowired. - Ambiguity: qualifier on the parameter, or a single
@Primaryas the boring default. - Cycles: constructor cycles fail fast. Field injection used to hide them behind an early reference.
Step-by-step explanation
- Define
PricingClientas a one-method interface at the service boundary. - Assign
private finalfields from a single constructor. Skip@Autowired. - Stereotype the implementation with
@Serviceso component scan registers it. - If startup reports a duplicate type, add
@Qualifierand cover the choice with a unit test that does not boot Spring.
Informative example
Price, then place. The test implements the interface with a lambda.
public interface PricingClient {int quoteCents(String sku, int qty);}@Servicepublic class OrderService {private final PricingClient pricing;public OrderService(PricingClient pricing) {this.pricing = pricing;}public PlacedOrder place(String sku, int qty) {return new PlacedOrder(sku, pricing.quoteCents(sku, qty));}}record PlacedOrder(String sku, int amountCents) {}
Two beans need a qualifier at the injection point:
@Bean @Qualifier("promo")PricingClient promoPrice() { return (sku, qty) -> 3999; }@Serviceclass PromoOrderService {private final PricingClient pricing;PromoOrderService(@Qualifier("promo") PricingClient pricing) {this.pricing = pricing;}}
Real-world use
In TechLearningPro Orders, place asks PricingClient for cents and an inventory port to reserve the SKU. Promo tests pass a lambda and never bind port 8080. The HTTP client behind the interface can change later. A constructor with six services means the class is also doing tax, fraud, mail, and audit — split it.
Security implications
The container wires whatever type matches. A sloppy default sends Orders to the wrong payment host.
- Inject the pricing port into the service and the service into the controller. A controller holding a
DataSourceor an admin client will eventually expose it. - Do not store the current user or a bearer token on a singleton field. The next request shares that instance.
- A lazy proxy that hides a cycle can run a security filter before its allow-list is set. Fail the boot.
Best practices
- One constructor and
finalfields. Depend on interfaces at service boundaries. - Put
@Qualifierbeside the business choice. Use@Primaryonly for the default. - Inject
Clockrather than callingInstant.now(), so tests freeze time. - Treat more than about four collaborators as a reason to split the type.
Common mistakes
new CatalogPricingClient()inside the service skips the container, so transactions and test fakes never apply.- Field
@Autowired, or mixing@RequiredArgsConstructorwith a second handwritten constructor so Spring picks the empty one. @Primaryleft on a sandbox payment client. Unqualified injection points follow it.allow-circular-referencesturned on to green the boot. One bean then sees the other mid-initialization.
Advanced interview questions
Interview Prep
Practice concise answers, then expand each card for the explanation.
1BeginnerQuestionWhy prefer constructor injection on Boot 3?+
Answer
final, and tests call new. A single constructor needs no @Autowired. Field injection hides the graph and needs reflection.2IntermediateQuestionWhat happens when two beans implement PricingClient?+
Answer
NoUniqueBeanDefinitionException at startup, unless the parameter has @Qualifier, one bean is @Primary, or you inject List<PricingClient>. The qualifier wins when both are present.3AdvancedQuestionBoot reports a dependency cycle. What do you change?+
Answer
ObjectProvider. spring.main.allow-circular-references=true is a migration switch, not the design of a new Orders service.Hands-on exercise
Lab. Constructor-inject PricingClient and assert place with (sku, qty) -> 4999. Add a second bean, read NoUniqueBeanDefinitionException, and fix it with @Qualifier("promo").
Summary
Orders injection is a constructor contract: PricingClient in, PlacedOrder out. Boot supplies the production client, tests supply a lambda, and a refused cycle protects you from a half-built bean.