Sobes.tech
Junior — Middle

How does Spring handle the situation when multiple components of the same type are defined in the context?

sobes.tech AI

Answer from AI

When in a Spring context there are multiple beans of the same type, and dependency injection occurs by type (for example, using @Autowired), ambiguity arises because Spring does not know which bean to choose.

How Spring handles this situation:

  1. NoUniqueBeanDefinitionException — if no explicit indication is given, Spring throws an exception, indicating multiple candidates.
  2. Using @Qualifier annotation: to specify the exact bean, you can use @Qualifier("beanName") together with @Autowired.
  3. Using the variable name: if the variable name matches the bean name, Spring may use the bean with that name.
  4. @Primary annotation: you can mark one bean as primary with @Primary, and it will be chosen by default.

Example:

@Component
@Primary
public class ServiceA implements MyService {}

@Component("serviceB")
public class ServiceB implements MyService {}

@Autowired
private MyService myService; // will inject ServiceA due to @Primary

@Autowired
@Qualifier("serviceB")
private MyService myServiceB; // will inject ServiceB

Thus, Spring requires explicit indication of which bean to use when multiple are present, to avoid ambiguity.

How does Spring handle the situation when multiple… - sobes.tech