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:
- By type: Spring searches for a bean whose type matches the field or constructor parameter type.
- By name: If there are multiple beans of the same type, Spring tries to select the bean with a name matching the field name.
- @Qualifier annotations: Allow explicitly specifying which bean to use when there are multiple candidates.
- @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.