Several implementations: @Qualifier and @Primary
45 min · Intermediate
Need help? Ask a tutor on WhatsApp (opens in a new tab)ShopLite prices a cart in several ways: no discount, a festival sale, a student card. Each rule is its own class. When checkout asks for "a discount rule", Spring must know which one to hand over.
One interface, several implementations
A candidate is a bean whose type matches what a constructor parameter asks for. With one candidate Spring injects it; with several, Spring needs a rule to choose.
FestivalDiscount and NoDiscount both implement DiscountPolicy, and both are beans. The runner asks for the two concrete classes, so each parameter has one candidate.
Example 1 · DiscountPolicy.java, FestivalDiscount.java, NoDiscount.java, PolicyListRunner.java
Runs in: the di-lab practice project (Spring Boot 4.1)
package com.shoplite.lab;
import java.math.BigDecimal;
public interface DiscountPolicy {
BigDecimal discountOn(BigDecimal amount);
String label();}
package com.shoplite.lab;
import java.math.BigDecimal;import java.math.RoundingMode;
import org.springframework.stereotype.Component;
@Componentpublic class FestivalDiscount implements DiscountPolicy {
@Override public BigDecimal discountOn(BigDecimal amount) { return amount.multiply(new BigDecimal("0.10")).setScale(2, RoundingMode.HALF_UP); // 10% off }
@Override public String label() { return "Diwali festival 10%"; }}
package com.shoplite.lab;
import java.math.BigDecimal;
import org.springframework.stereotype.Component;
@Componentpublic class NoDiscount implements DiscountPolicy {
@Override public BigDecimal discountOn(BigDecimal amount) { return BigDecimal.ZERO.setScale(2); }
@Override public String label() { return "No discount"; }}
package com.shoplite.lab;
import java.math.BigDecimal;
import org.springframework.boot.CommandLineRunner;import org.springframework.stereotype.Component;
@Componentpublic class PolicyListRunner implements CommandLineRunner {
private final FestivalDiscount festival; private final NoDiscount none;
public PolicyListRunner(FestivalDiscount festival, NoDiscount none) { // asks for the classes this.festival = festival; this.none = none; }
@Override public void run(String... args) { BigDecimal cart = new BigDecimal("2499.00"); for (DiscountPolicy policy : new DiscountPolicy[] {festival, none}) { System.out.println(policy.label() + " on Rs " + cart + ": Rs " + policy.discountOn(cart) + " off"); } }}Diwali festival 10% on Rs 2499.00: Rs 249.90 off No discount on Rs 2499.00: Rs 0.00 off
What this code does
- Two classes implement
DiscountPolicy, and each is a bean:festivalDiscountandnoDiscount. - The runner asks for the concrete classes, so each parameter has exactly one candidate and startup works. Money uses
BigDecimal, rounded to 2 places.
An implementation is a class that implements an interface. ShopLite prices carts with a DiscountPolicy interface: FestivalDiscount takes 10% off during Diwali, NoDiscount takes nothing off, and later a StudentDiscount takes 15%. The interface lets the checkout code stay the same while the rule changes.
With @Component on each class, Spring creates one bean per implementation. Asking for a concrete class is never a problem: exactly one bean has that type. The question starts when a class asks for the interface.
Two candidates: 'required a single bean, but 2 were found'
NoUniqueBeanDefinitionException is behind the startup report "required a single bean, but 2 were found". Spring will not guess between two candidates for one injection point.
CheckoutService asks for a DiscountPolicy, and two beans match. Start the app and read the report.
Example 2 · src/main/java/com/shoplite/lab/CheckoutService.java
Runs in: the di-lab practice project (Spring Boot 4.1)
package com.shoplite.lab;
import java.math.BigDecimal;
import org.springframework.stereotype.Service;
@Servicepublic class CheckoutService {
private final DiscountPolicy discountPolicy;
public CheckoutService(DiscountPolicy discountPolicy) { this.discountPolicy = discountPolicy; }
public String checkout(BigDecimal amount) { BigDecimal discount = discountPolicy.discountOn(amount); return discountPolicy.label() + ": Rs " + amount + " - Rs " + discount + " = Rs " + amount.subtract(discount); }}2026-10-16T10:23:20.811+05:30 ERROR 23940 --- [di-lab] [ main] o.s.b.d.LoggingFailureAnalysisReporter : *************************** APPLICATION FAILED TO START *************************** Description: Parameter 0 of constructor in com.shoplite.lab.CheckoutService required a single bean, but 2 were found: - festivalDiscount: defined in file [C:\work\di-lab\target\classes\com\shoplite\lab\FestivalDiscount.class] - noDiscount: defined in file [C:\work\di-lab\target\classes\com\shoplite\lab\NoDiscount.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
CheckoutServiceasks for the interface. Both beans match, so Spring stops and names them:festivalDiscountandnoDiscount. The classes are those from Example 1; the runner callscheckout(2499.00).- The parameter is called
discountPolicy, which matches neither bean name, so the parameter-name rule cannot help either. Your file paths will differ.
The exception message reads "expected single matching bean but found 2: festivalDiscount,noDiscount". The Action block lists the three fixes: mark one bean @Primary, accept all of them (a List), or use @Qualifier.
The report also mentions the -parameters compiler flag. Spring Boot's Maven setup already turns it on; the line is there because one more rule depends on parameter names, explained in the next section.
@Primary for the default, @Qualifier for a specific bean
@Primary marks one bean as the default: whenever a class asks for the interface without saying more, it gets this bean. @Qualifier("name") on a parameter asks for the bean with exactly that name instead.
Mark NoDiscount as @Primary and the unchanged CheckoutService starts. A second service asks for the festival rule by name with @Qualifier.
Example 3 · NoDiscount.java, FestivalCheckoutService.java, CheckoutRunner.java
Runs in: the di-lab practice project (Spring Boot 4.1)
package com.shoplite.lab;
import java.math.BigDecimal;
import org.springframework.context.annotation.Primary;import org.springframework.stereotype.Component;
@Component@Primary // the default when someone asks for "a DiscountPolicy"public class NoDiscount implements DiscountPolicy {
@Override public BigDecimal discountOn(BigDecimal amount) { return BigDecimal.ZERO.setScale(2); }
@Override public String label() { return "No discount"; }}
package com.shoplite.lab;
import java.math.BigDecimal;
import org.springframework.beans.factory.annotation.Qualifier;import org.springframework.stereotype.Service;
@Servicepublic class FestivalCheckoutService {
private final DiscountPolicy discountPolicy;
public FestivalCheckoutService(@Qualifier("festivalDiscount") DiscountPolicy discountPolicy) { this.discountPolicy = discountPolicy; }
public String checkout(BigDecimal amount) { BigDecimal discount = discountPolicy.discountOn(amount); return discountPolicy.label() + ": Rs " + amount + " - Rs " + discount + " = Rs " + amount.subtract(discount); }}
package com.shoplite.lab;
import java.math.BigDecimal;
import org.springframework.boot.CommandLineRunner;import org.springframework.stereotype.Component;
@Componentpublic class CheckoutRunner implements CommandLineRunner {
private final CheckoutService normal; private final FestivalCheckoutService festival;
public CheckoutRunner(CheckoutService normal, FestivalCheckoutService festival) { this.normal = normal; this.festival = festival; }
@Override public void run(String... args) { BigDecimal cart = new BigDecimal("2499.00"); System.out.println("Normal day: " + normal.checkout(cart)); System.out.println("Festival: " + festival.checkout(cart)); }}Normal day: No discount: Rs 2499.00 - Rs 0.00 = Rs 2499.00 Festival: Diwali festival 10%: Rs 2499.00 - Rs 249.90 = Rs 2249.10
What this code does
@PrimaryonNoDiscountmakes it the default, so the unchangedCheckoutServicefrom Example 2 now starts and gets no discount.FestivalCheckoutServiceasks for@Qualifier("festivalDiscount")and gets the festival rule, even though another bean is primary.- Both imports matter:
@Primaryis inorg.springframework.context.annotation,@Qualifierinorg.springframework.beans.factory.annotation.
Spring decides in this order: a @Qualifier on the parameter wins; otherwise a @Primary bean; otherwise a bean whose name equals the parameter name (DiscountPolicy festivalDiscount gets festivalDiscount); otherwise startup fails.
Do not rely on the parameter-name rule. Renaming a parameter in a refactoring silently changes which bean you get. Use @Primary for the normal choice and @Qualifier for the exceptions, so the choice is written down.
Predict the output
Predict the injected bean
NoDiscount and FestivalDiscount are both beans. Which one is injected?
Round 1 of 3
NoDiscount is @Primary, and the parameter is named festivalDiscount.
@Qualifier value is a bean name, so a typo fails at startup with "No qualifying bean". Keep bean names stable, or set them on purpose with @Component("festival").Injecting List<DiscountPolicy> and Map<String, DiscountPolicy>
List<T> and Map<String, T> parameters receive every bean of type T; the map is keyed by bean name. Neither needs @Primary or @Qualifier, because the class asked for all of them.
Add a third rule, StudentDiscount, as one new class. BestDiscountFinder receives a List and a Map of all the policies.
Example 4 · StudentDiscount.java, BestDiscountFinder.java, DiscountRunner.java
Runs in: the di-lab practice project (Spring Boot 4.1)
package com.shoplite.lab;
import java.math.BigDecimal;import java.math.RoundingMode;
import org.springframework.stereotype.Component;
@Componentpublic class StudentDiscount implements DiscountPolicy {
@Override public BigDecimal discountOn(BigDecimal amount) { return amount.multiply(new BigDecimal("0.15")).setScale(2, RoundingMode.HALF_UP); // 15% off }
@Override public String label() { return "Student ID 15%"; }}
package com.shoplite.lab;
import java.math.BigDecimal;import java.util.Comparator;import java.util.List;import java.util.Map;
import org.springframework.stereotype.Service;
@Servicepublic class BestDiscountFinder {
private final List<DiscountPolicy> allPolicies; private final Map<String, DiscountPolicy> policiesByName;
public BestDiscountFinder(List<DiscountPolicy> allPolicies, Map<String, DiscountPolicy> policiesByName) { this.allPolicies = allPolicies; this.policiesByName = policiesByName; }
public DiscountPolicy bestFor(BigDecimal amount) { return allPolicies.stream() .max(Comparator.comparing(p -> p.discountOn(amount))) .orElseThrow(); }
public DiscountPolicy byName(String beanName) { DiscountPolicy policy = policiesByName.get(beanName); if (policy == null) { throw new IllegalArgumentException("No discount policy named " + beanName); } return policy; }
public List<String> names() { return policiesByName.keySet().stream().sorted().toList(); }}
package com.shoplite.lab;
import java.math.BigDecimal;
import org.springframework.boot.CommandLineRunner;import org.springframework.stereotype.Component;
@Componentpublic class DiscountRunner implements CommandLineRunner {
private final BestDiscountFinder finder;
public DiscountRunner(BestDiscountFinder finder) { this.finder = finder; }
@Override public void run(String... args) { BigDecimal cart = new BigDecimal("2499.00"); System.out.println("Policies: " + finder.names()); DiscountPolicy best = finder.bestFor(cart); System.out.println("Best for Rs " + cart + ": " + best.label() + ", Rs " + best.discountOn(cart) + " off"); System.out.println("Chosen by name: " + finder.byName("festivalDiscount").label()); }}Policies: [festivalDiscount, noDiscount, studentDiscount] Best for Rs 2499.00: Student ID 15%, Rs 374.85 off Chosen by name: Diwali festival 10%
What this code does
- A third rule,
StudentDiscount, is added as one new class. Nothing else changes, and there is no@Primaryin this example. - The
Listholds all three policies;bestForkeeps the one with the largest discount on Rs 2499.00, which is the student rule (Rs 374.85). - The
Mapkeys are the bean names, sobyName("festivalDiscount")picks one rule from a string, as a request parameter would.
A list fits rules that all apply, such as order checks, or a "pick the best" loop. A map fits a choice made at run time from user input, such as a payment method named in a request. The list order follows @Order(1), @Order(2) on the classes; without it, do not rely on any order.
Adding a new rule is then just adding one new @Component class: no if chain to edit. This is the open/closed idea: open for new rules, closed for changes to working code.
Optional dependencies with ObjectProvider
ObjectProvider<T> is a handle to a bean that may not exist. It is always there: getIfAvailable() returns the bean or null, and ifAvailable(bean -> ...) runs code only when the bean exists.
OrderConfirmation sends an SMS when SmsNotifier is a bean, and gives loyalty points only when LoyaltyPoints is a bean. Today only the SMS bean exists.
Example 5 · LoyaltyPoints.java, SmsNotifier.java, OrderConfirmation.java, ConfirmRunner.java
Runs in: the di-lab practice project (Spring Boot 4.1)
package com.shoplite.lab;
// Not a bean yet: the loyalty programme starts next monthpublic class LoyaltyPoints {
public int pointsFor(int amount) { return amount / 100; }}
package com.shoplite.lab;
import org.springframework.stereotype.Component;
@Componentpublic class SmsNotifier {
public void send(String phone, String text) { System.out.println("SMS to " + phone + ": " + text); }}
package com.shoplite.lab;
import org.springframework.beans.factory.ObjectProvider;import org.springframework.stereotype.Service;
@Servicepublic class OrderConfirmation {
private final ObjectProvider<SmsNotifier> sms; private final ObjectProvider<LoyaltyPoints> loyalty;
public OrderConfirmation(ObjectProvider<SmsNotifier> sms, ObjectProvider<LoyaltyPoints> loyalty) { this.sms = sms; this.loyalty = loyalty; }
public void confirm(String phone, int amount) { sms.ifAvailable(notifier -> notifier.send(phone, "Order of Rs " + amount + " confirmed"));
LoyaltyPoints points = loyalty.getIfAvailable(); if (points == null) { System.out.println("No loyalty programme yet, so no points"); } else { System.out.println("Points earned: " + points.pointsFor(amount)); } }}
package com.shoplite.lab;
import org.springframework.boot.CommandLineRunner;import org.springframework.stereotype.Component;
@Componentpublic class ConfirmRunner implements CommandLineRunner {
private final OrderConfirmation confirmation;
public ConfirmRunner(OrderConfirmation confirmation) { this.confirmation = confirmation; }
@Override public void run(String... args) { confirmation.confirm("9845012345", 2499); }}SMS to 9845012345: Order of Rs 2499 confirmed No loyalty programme yet, so no points
What this code does
SmsNotifieris a bean, soifAvailableruns and the SMS line prints.LoyaltyPointshas no annotation, sogetIfAvailable()returnsnulland the service prints the fallback line.- Next month, adding
@ComponenttoLoyaltyPointsturns the points on without changingOrderConfirmation.
An optional dependency is one the class can work without, for example a loyalty-points service that starts next month. A plain constructor parameter would make startup fail while the bean is missing, so ask for an ObjectProvider instead. getObject() returns the bean and fails if there is none.
Optional<LoyaltyPoints> as a parameter works too. ObjectProvider can also hand out a new object on each call for prototype beans, which the next lesson uses.
Fix the error
Fix the optional bean
Read the real error, then pick the line that fixes it.
LoyaltyPoints is not a bean yet, but orders must still work.
Error
NoSuchBeanDefinitionException: No qualifying bean of type 'com.shoplite.lab.LoyaltyPoints' available
Next step
Check your understanding
12 quick questions