Skip to content
Tutorials Center
My learning

Topics

Lesson 9 of 66 ยท Inversion of Control and Beans

Qualifiers, @Primary and Collections

Resolve multiple Spring bean candidates with @Primary and @Qualifier, inject all beans as a List or Map, use ObjectProvider, and avoid circular dependencies.

Injection by type works beautifully until two beans have the same type. Imagine an interface PaymentGateway with a card implementation and a bank-transfer implementation. A constructor asking for one PaymentGateway is now ambiguous, and the container refuses to guess: the application fails to start with NoUniqueBeanDefinitionException. This lesson is about the tools that resolve that ambiguity, and about the related cases where you actually want all the candidates, or maybe none.

You will learn @Primary, @Qualifier, name matching, injecting a List or Map of beans, ObjectProvider, optional dependencies, and why circular dependencies fail in Boot. The Spring snippets are read-only. The runnable TryIts are plain-Java stand-ins that implement the same resolution rules.

The ambiguity

Java
public interface PaymentGateway {
    String name();
    void charge(int cents);
}

@Component
class CardGateway implements PaymentGateway { ... }

@Component
class BankTransferGateway implements PaymentGateway { ... }

@Service
class CheckoutService {
    CheckoutService(PaymentGateway gateway) { ... }   // which one?
}

Both components match the parameter type, so the container has two candidates and no rule to choose. Spring gives you four ways to pick, and the container tries them in a fixed order.

How Spring picks one candidate

@Primary One bean marked as the default choice.
@Qualifier The injection point asks for a label.
Name match The parameter name equals a bean name.
Still two? NoUniqueBeanDefinitionException at startup.

A @Qualifier at the injection point wins over @Primary.

1 / 2

@Primary: the default choice

Mark one candidate as the preferred bean for its type:

Java
@Component
@Primary
class CardGateway implements PaymentGateway { ... }

Now every injection point asking for a plain PaymentGateway gets CardGateway, and BankTransferGateway is still available to anyone who asks for it specifically. @Primary suits the "99% of the time use this one" case. It also works on a @Bean method, and it is how an application overrides a default supplied by a library: you define your own bean and mark it primary.

@Qualifier: ask for a specific one

@Qualifier names the bean you want at the injection point:

Java
@Service
class RefundService {
    private final PaymentGateway gateway;

    RefundService(@Qualifier("bankTransferGateway") PaymentGateway gateway) {
        this.gateway = gateway;
    }
}

The bean name of a scanned component is its simple class name with a lowercase first letter, so BankTransferGateway becomes bankTransferGateway. For a @Bean method it is the method name (see @Configuration and @Bean). A qualifier at the injection point beats @Primary, so a single special consumer can opt out of the default.

Bean names are fragile strings: rename the class and the qualifier silently stops matching. A sturdier approach is a custom qualifier annotation, meta-annotated with @Qualifier:

Java
@Target({ElementType.FIELD, ElementType.METHOD, ElementType.PARAMETER, ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Qualifier
public @interface Bank {}

@Component @Bank class BankTransferGateway implements PaymentGateway { ... }

RefundService(@Bank PaymentGateway gateway) { ... }

A rename now causes a compile error instead of a runtime surprise.

The last fallback: the parameter name

If a type has several candidates, no @Primary and no qualifier, Spring finally compares the parameter (or field) name with the bean names. A parameter called cardGateway matches the bean cardGateway. This works because Boot builds with the -parameters compiler flag, but it is a convenience, not a design: a refactoring tool can rename the parameter and quietly change which bean you get. Treat it as a backup, and use @Primary or @Qualifier when the choice matters.

The next TryIt implements exactly this decision order so you can see which rule wins.

Java A candidate resolver stand-in

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

What is real: the decision order and the error message wording style. What is the stand-in: the real resolver also considers generics (Repository<User> versus Repository<Order>), custom qualifier annotations, @Priority and autowire-candidate flags.

Injecting all candidates: List and Map

Sometimes you want every implementation, not one. Ask for a collection and Spring injects all matching beans:

Java
@Service
class PaymentRouter {
    private final List<PaymentGateway> gateways;
    private final Map<String, PaymentGateway> byName;

    PaymentRouter(List<PaymentGateway> gateways, Map<String, PaymentGateway> byName) {
        this.gateways = gateways;
        this.byName = byName;
    }
}

For a Map<String, T> the keys are the bean names. For a List<T> the order is the registration order unless you control it: @Order(10) on the classes (lower values first), or implement Ordered. This is the plug-in pattern: add one more implementation class and the router picks it up without any change. Typical uses are validation rules, event handlers, payment methods and import formats.

Two details to remember. If no bean matches, a required List<T> injection fails, just like a single missing bean. And when you want to be told about a missing bean rather than fail, use one of the optional forms below.

Optional dependencies and ObjectProvider

A dependency can be absent and that is fine. There are three ways to express it:

Java
// 1. Optional: empty when no bean exists
CheckoutService(Optional<FraudChecker> fraudChecker) { ... }

// 2. @Nullable: null when no bean exists
CheckoutService(@Nullable FraudChecker fraudChecker) { ... }

// 3. ObjectProvider: the most flexible
CheckoutService(ObjectProvider<FraudChecker> fraudChecker) {
    fraudChecker.ifAvailable(checker -> checker.screen(...));
}

ObjectProvider<T> is the Swiss army knife. It defers the lookup until you ask, so it works with prototype beans (see Bean Scopes and Lifecycle). Its methods include getIfAvailable(), getIfUnique(), getObject() (throws if absent), ifAvailable(consumer), orderedStream() and stream(). It also helps break startup cycles because the dependency is not resolved at construction time.

Java Collections and optional injection

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

The first loop shows why order matters: noSpaces (order 10) runs before notBlank (order 20). The lists and maps here are built by hand, whereas Spring builds them from the bean registry.

Circular dependencies

If A needs B in its constructor and B needs A, neither can be built first. Since Boot 2.6 the container refuses by default and fails the start-up with a message that prints the cycle and says A -> B -> A. You could allow cycles with spring.main.allow-circular-references=true, which relies on injecting half-built beans through fields or setters, but that only hides a design problem.

Better fixes, from best to least good:

  1. Rethink the design. A cycle usually means two classes share a responsibility. Extract the shared part into a third bean that both use.
  2. Introduce an event. Instead of A calling B directly, A publishes an event that B listens for (Application Events and Runners).
  3. Inject lazily. Use ObjectProvider<A> or @Lazy on one parameter so it is resolved on first use. Use this only when a redesign is not possible.

The cycle is simple to detect by walking dependencies. This is roughly what the container does as it creates beans.

Java Detecting a circular dependency

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

The real error report draws the cycle in a similar way and names the constructor parameters, which is why reading it carefully usually points straight to the guilty class. You will practice that in Common Mistakes and Debugging Startup Failures.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Two beans implement PaymentGateway and neither is @Primary. A constructor takes one PaymentGateway gateway. What happens at startup?

    With multiple candidates Spring tries a qualifier, then @Primary, then the parameter name. If none helps, it refuses to guess and the startup fails.
  2. 2. One bean is @Primary and an injection point uses @Qualifier("bankTransferGateway"). Which bean does that injection point receive?

    A qualifier at the injection point is more specific than a global default, so it wins over @Primary.
  3. 3. What are the keys of an injected Map<String, PaymentGateway>?

    Spring fills a Map<String, T> with every matching bean, keyed by its bean name.
  4. 4. Which choice is the best first response to a circular dependency between two services?

    A cycle usually signals a design problem. Allowing cycles only hides it, and the lazy and event-based approaches are second-best choices.

Summary

  • Several beans of one type make injection ambiguous; Spring checks a qualifier, then @Primary, then the parameter name, then fails with NoUniqueBeanDefinitionException.
  • @Primary marks the default; @Qualifier (or a custom qualifier annotation) selects a specific bean and wins over @Primary.
  • Inject a List<T> for all beans (order with @Order) or a Map<String, T> keyed by bean name to build plug-in style designs.
  • Optional, @Nullable and especially ObjectProvider express optional dependencies and lazy lookup.
  • Circular constructor dependencies fail by default in Boot; fix the design instead of enabling cycles.

Next: Conditional Beans.