Sobes.tech
Junior — Middle

How does Spring decide which object to inject as a dependency?

sobes.tech AI

Answer from AI

Spring decides which object to inject into a dependency using the autowiring mechanism. The main ways to select a bean:

  1. By type: Spring searches for a bean whose type matches the field or constructor parameter type.
  2. By name: If there are multiple beans of the same type, Spring tries to select the bean with a name matching the field name.
  3. @Qualifier annotations: Allow explicitly specifying which bean to use when there are multiple candidates.
  4. @Primary: An annotation on a bean that makes it the preferred choice in case of conflicts.

If it is not possible to unambiguously determine the bean, Spring throws an exception.

Example:

@Autowired
@Qualifier("myServiceImpl")
private MyService service;

Here, it explicitly specifies which bean to inject.

How does Spring decide which object to inject as a… - sobes.tech