Practice: dependency injection and beans
A review of this module. Skip it if you feel confident; the next module does not need it.
Fix the mistakes
The slips that cost marks in this module. Spot each one, then check the fix.
Almost every bean wiring failure is one of three things: a bean Spring never created, two beans where one was expected, or beans that need each other in a loop. Each has a recognisable report at startup and a short, reliable fix.
Predicting which bean gets injected
One constructor uses every rule: @Primary, a parameter name, @Qualifier, List, Map and ObjectProvider. Predict each of the six printed lines before you read the output.
Example 1 · Courier.java, SpeedPostCourier.java, LocalCourier.java, PickupPointCourier.java, SmsSender.java, PredictRunner.java
Runs in: the di-lab practice project (Spring Boot 4.1)
package com.shoplite.lab;
public interface Courier { String name();}
package com.shoplite.lab;
import org.springframework.context.annotation.Primary;import org.springframework.stereotype.Component;
@Component@Primarypublic class SpeedPostCourier implements Courier {
@Override public String name() { return "Speed Post"; }}
package com.shoplite.lab;
import org.springframework.stereotype.Component;
@Componentpublic class LocalCourier implements Courier {
@Override public String name() { return "Local courier"; }}
package com.shoplite.lab;
import org.springframework.stereotype.Component;
@Componentpublic class PickupPointCourier implements Courier {
@Override public String name() { return "Pickup point"; }}
package com.shoplite.lab;
// No annotation: not a beanpublic class SmsSender {}
package com.shoplite.lab;
import java.util.List;import java.util.Map;import java.util.TreeMap;
import org.springframework.beans.factory.ObjectProvider;import org.springframework.beans.factory.annotation.Qualifier;import org.springframework.boot.CommandLineRunner;import org.springframework.stereotype.Component;
@Componentpublic class PredictRunner implements CommandLineRunner {
private final Courier courier; private final Courier localCourier; private final Courier chosen; private final List<Courier> all; private final Map<String, Courier> byName; private final ObjectProvider<SmsSender> sms;
public PredictRunner(Courier courier, Courier localCourier, @Qualifier("pickupPointCourier") Courier chosen, List<Courier> all, Map<String, Courier> byName, ObjectProvider<SmsSender> sms) { this.courier = courier; this.localCourier = localCourier; this.chosen = chosen; this.all = all; this.byName = byName; this.sms = sms; }
@Override public void run(String... args) { System.out.println("1. courier -> " + courier.name()); System.out.println("2. localCourier -> " + localCourier.name()); System.out.println("3. @Qualifier -> " + chosen.name()); System.out.println("4. List size -> " + all.size()); System.out.println("5. Map keys -> " + new TreeMap<>(byName).keySet()); System.out.println("6. SmsSender -> " + sms.getIfAvailable()); }}1. courier -> Speed Post 2. localCourier -> Speed Post 3. @Qualifier -> Pickup point 4. List size -> 3 5. Map keys -> [localCourier, pickupPointCourier, speedPostCourier] 6. SmsSender -> null
What this code does
- Line 1: three candidates, no qualifier, so the
@Primarybean wins: Speed Post. Line 2 is the surprise: the parameter is namedlocalCourier, but@Primaryis checked before the parameter name, so it is Speed Post again. - Line 3: the
@Qualifierwins over@Primary. Lines 4 and 5: theListandMapget all three couriers; the map keys are bean names (sorted here with aTreeMap). - Line 6:
SmsSenderis not a bean, so the provider returnsnullinstead of stopping startup.
For each constructor parameter Spring first collects the candidates, the beans of the right type. One candidate is simply injected. With several, Spring goes down a fixed list: a @Qualifier on the parameter, then a @Primary bean, then a bean whose name equals the parameter name. If none decides, startup fails.
List<T> and Map<String, T> skip the list: they receive every candidate. ObjectProvider<T> never fails at startup; getIfAvailable() returns null when there is no bean.
Mistake 1: a bean Spring never created
GstFormatter has @Component, yet InvoiceService cannot find it. Compare the two packages and read the startup report.
Example 2 · GstFormatter.java, InvoiceService.java
Runs in: the di-lab practice project (Spring Boot 4.1)
package com.shoplite.tools;
import org.springframework.stereotype.Component;
@Componentpublic class GstFormatter {
public String withGst(int amount) { return "Rs " + amount + " + 18% GST = Rs " + (amount + amount * 18 / 100); }}
package com.shoplite.lab;
import com.shoplite.tools.GstFormatter;import org.springframework.stereotype.Service;
@Servicepublic class InvoiceService {
private final GstFormatter formatter;
public InvoiceService(GstFormatter formatter) { this.formatter = formatter; }
public String line(int amount) { return "Invoice total " + formatter.withGst(amount); }}2026-10-16T10:38:42.632+05:30 ERROR 12216 --- [di-lab] [ main] o.s.b.d.LoggingFailureAnalysisReporter : *************************** APPLICATION FAILED TO START *************************** Description: Parameter 0 of constructor in com.shoplite.lab.InvoiceService required a bean of type 'com.shoplite.tools.GstFormatter' that could not be found. Action: Consider defining a bean of type 'com.shoplite.tools.GstFormatter' in your configuration.
What this code does
GstFormatterhas@Component, yet Spring says no such bean exists. Its package,com.shoplite.tools, is not belowcom.shoplite.lab, so scanning never looked there.- Moving the class to
com.shoplite.lab.billing(and updating the import inInvoiceService) fixes it. Practice 2 does exactly that.
The report "required a bean of type 'X' that could not be found" means no bean of type X exists. Three causes cover almost every case: X has no stereotype annotation, the annotation sits on an interface instead of the class, or X is in a package that component scanning never visits.
Scanning starts at the main class's package (com.shoplite.lab in di-lab) and goes down into its sub-packages. A class in com.shoplite.tools is a sibling package, so it is never found, even with @Component. Move it under the main package, for example com.shoplite.lab.billing; in ShopLite every feature package is below com.shoplite, where the main class lives.
Mistake 2: two beans of one type
PriceFormatter is a @Component, and AppConfig also returns one from a @Bean method. ReceiptService asks for a PriceFormatter.
Example 3 · PriceFormatter.java, AppConfig.java, ReceiptService.java
Runs in: the di-lab practice project (Spring Boot 4.1)
package com.shoplite.lab;
import org.springframework.stereotype.Component;
@Componentpublic class PriceFormatter {
public String format(int rupees) { return "Rs " + rupees + ".00"; }}
package com.shoplite.lab;
import org.springframework.context.annotation.Bean;import org.springframework.context.annotation.Configuration;
@Configurationpublic class AppConfig {
@Bean public PriceFormatter rupeeFormatter() { // a second PriceFormatter bean return new PriceFormatter(); }}
package com.shoplite.lab;
import org.springframework.stereotype.Service;
@Servicepublic class ReceiptService {
private final PriceFormatter formatter;
public ReceiptService(PriceFormatter formatter) { this.formatter = formatter; }
public String total(int rupees) { return "Total: " + formatter.format(rupees); }}2026-10-16T10:38:48.572+05:30 ERROR 2204 --- [di-lab] [ main] o.s.b.d.LoggingFailureAnalysisReporter : *************************** APPLICATION FAILED TO START *************************** Description: Parameter 0 of constructor in com.shoplite.lab.ReceiptService required a single bean, but 2 were found: - priceFormatter: defined in file [C:\work\di-lab\target\classes\com\shoplite\lab\PriceFormatter.class] - rupeeFormatter: defined by method 'rupeeFormatter' in class path resource [com/shoplite/lab/AppConfig.class] This may be due to missing parameter name information Action: Consider marking one of the beans as @Primary, updating the consumer to accept multiple beans, or using @Qualifier to identify the bean that should be consumed Ensure that your compiler is configured to use the '-parameters' flag. You may need to update both your build tool settings as well as your IDE. (See https://github.com/spring-projects/spring-framework/wiki/Spring-Framework-6.1-Release-Notes#parameter-name-retention)
What this code does
- The two candidates are
priceFormatter(the scanned class) andrupeeFormatter(the@Beanmethod). Both arePriceFormatterobjects, so Spring cannot choose. - The parameter is named
formatter, which matches neither bean name. DeletingAppConfig.rupeeFormatter()leaves one bean, and the app printsTotal: Rs 2499.00(Practice 4).
"required a single bean, but 2 were found" lists the candidates and where each was defined. A common surprise is that both are the same class, registered twice. Read the "defined in" part of each line: "defined in file [...PriceFormatter.class]" is a scanned component, and "defined by method 'rupeeFormatter'" is a @Bean method.
When one is an accident, delete it. When both are wanted, as with two discount rules, use @Primary or @Qualifier.
Mistake 3: a loop hidden by field injection
Three services hold each other through @Autowired fields, so no constructor shows the loop. Read the report, then rebuild them with constructors and a small OrderTotals bean.
Example 4 · OrderService.java, PaymentService.java, ReceiptMailer.java
Runs in: the di-lab practice project (Spring Boot 4.1)
package com.shoplite.lab;
import org.springframework.beans.factory.annotation.Autowired;import org.springframework.stereotype.Service;
@Servicepublic class OrderService {
@Autowired private PaymentService paymentService;
public String place(String orderId) { return paymentService.charge(orderId); }}
package com.shoplite.lab;
import org.springframework.beans.factory.annotation.Autowired;import org.springframework.stereotype.Service;
@Servicepublic class PaymentService {
@Autowired private ReceiptMailer receiptMailer;
public String charge(String orderId) { return receiptMailer.mail(orderId); }}
package com.shoplite.lab;
import org.springframework.beans.factory.annotation.Autowired;import org.springframework.stereotype.Component;
@Componentpublic class ReceiptMailer {
@Autowired private OrderService orderService; // only to read the order total
public String mail(String orderId) { return "Receipt mailed for " + orderId; }}2026-10-16T10:38:54.828+05:30 ERROR 6212 --- [di-lab] [ main] o.s.b.d.LoggingFailureAnalysisReporter : *************************** APPLICATION FAILED TO START *************************** Description: The dependencies of some of the beans in the application context form a cycle: ┌─────┐ | orderService (field private com.shoplite.lab.PaymentService com.shoplite.lab.OrderService.paymentService) ↑ ↓ | paymentService (field private com.shoplite.lab.ReceiptMailer com.shoplite.lab.PaymentService.receiptMailer) ↑ ↓ | receiptMailer (field private com.shoplite.lab.OrderService com.shoplite.lab.ReceiptMailer.orderService) └─────┘ Action: Relying upon circular references is discouraged and they are prohibited by default. Update your application to remove the dependency cycle between beans. As a last resort, it may be possible to break the cycle automatically by setting spring.main.allow-circular-references to true.
What this code does
- Three beans form a loop through fields: order → payment → receipt mailer → order. With fields, the report names each field, such as
ReceiptMailer.orderService. - Nothing in the code looked wrong, because field injection hides dependencies. Spring Boot still stops at startup.
Example 5 · OrderTotals.java, ReceiptMailer.java, PaymentService.java, OrderService.java, PlaceRunner.java
Runs in: the di-lab practice project (Spring Boot 4.1)
package com.shoplite.lab;
import org.springframework.stereotype.Component;
@Componentpublic class OrderTotals {
public int totalOf(String orderId) { return 1798; // pretend: sum of the order's items }}
package com.shoplite.lab;
import org.springframework.stereotype.Component;
@Componentpublic class ReceiptMailer {
private final OrderTotals totals;
public ReceiptMailer(OrderTotals totals) { this.totals = totals; }
public String mail(String orderId) { return "Receipt mailed for " + orderId + " (Rs " + totals.totalOf(orderId) + ")"; }}
package com.shoplite.lab;
import org.springframework.stereotype.Service;
@Servicepublic class PaymentService {
private final ReceiptMailer receiptMailer;
public PaymentService(ReceiptMailer receiptMailer) { this.receiptMailer = receiptMailer; }
public String charge(String orderId) { return receiptMailer.mail(orderId); }}
package com.shoplite.lab;
import org.springframework.stereotype.Service;
@Servicepublic class OrderService {
private final PaymentService paymentService;
public OrderService(PaymentService paymentService) { this.paymentService = paymentService; }
public String place(String orderId) { return paymentService.charge(orderId); }}
package com.shoplite.lab;
import org.springframework.boot.CommandLineRunner;import org.springframework.stereotype.Component;
@Componentpublic class PlaceRunner implements CommandLineRunner {
private final OrderService orders;
public PlaceRunner(OrderService orders) { this.orders = orders; }
@Override public void run(String... args) { System.out.println(orders.place("ORD-21")); }}Receipt mailed for ORD-21 (Rs 1798)
What this code does
- All four classes now use constructor injection with
finalfields, so every dependency is visible. ReceiptMailerdepends on the smallOrderTotalsbean instead ofOrderService. The chain is a line: order → payment → receipt mailer → order totals.
With field injection a dependency loop is easy to miss: the classes have no constructors, so nothing looks wrong. Spring Boot still refuses it at startup, and for fields the report names each field that closes the loop.
Convert the classes to constructor injection first: the loop then shows up as constructors that need each other. Then ask what the last class in the loop really needs. Here ReceiptMailer holds OrderService only to read the order total, so a small OrderTotals bean gives it that and the loop becomes a line. Do not "fix" a loop with spring.main.allow-circular-references=true; it hides the design problem until it causes a bug.
Finish up
Mark complete & continue
Next: Mini project: ShopLite cart pricing with beans