Sobes.tech
Junior — Middle

How does Spring determine which component to inject as a dependency?

sobes.tech AI

Answer from AI

Spring determines which component to inject into a dependency using the Inversion of Control (IoC) mechanism and the Dependency Injection (DI) container. The main ways to select a component:

  • 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, a specific bean can be specified by name using the @Qualifier annotation.
  • By annotations: components are marked with annotations like @Component, @Service, @Repository, etc., so Spring can detect them.

If there are multiple candidates in the context and @Qualifier is not specified, an error occurs. You can also use the @Primary annotation to designate a preferred bean.

Example:

@Service
public class UserService {
    private final UserRepository userRepository;

    public UserService(@Qualifier("userRepo") UserRepository userRepository) {
        this.userRepository = userRepository;
    }
}

Here, Spring will inject the bean named "userRepo" into the dependency.

How does Spring determine which component to inject… - sobes.tech