SteelReed

Search

Search posts, questions…

Spring BootQuestion 5 / 26

Middle

Two beans implement the same interface. How do you inject the one you want?

Short answer

Spring resolves beans by type; with several candidates and nothing to pick one, startup fails with NoUniqueBeanDefinitionException. Pick with @Primary, @Qualifier, the parameter name, or inject them all as List<T>/Map<String, T>.

yesnoyesnonoInject PaymentGatewayHas @Qualifier?Bean by qualifierHas @Primary?The @Primary beanParameter name = beanname?NoUniqueBeanDefinitionException

3 points to say:

  1. Several beans of one type and nothing to choose: NoUniqueBeanDefinitionException at startup.
  2. @Primary for the default bean, @Qualifier when the caller chooses; @Qualifier beats @Primary; the parameter name is the last fallback.
  3. Need every implementation: inject a List/Map (Strategy pattern), ordered with @Order.

Keep reading the deep dive

Create a free account to read the full explanation and follow-up questions, mark questions as studied and review them on a schedule.