Junior — Middle
How is dependency injection implemented in Spring Boot?
sobes.tech AI
Answer from AI
In Spring Boot, dependency injection is managed by the Spring IoC Container, which creates and wires objects (beans).
Main methods of dependency injection:
- Using
@Autowiredannotation — Spring automatically injects the required bean by type.
@Service
public class UserService {
@Autowired
private UserRepository userRepository;
}
- Using constructor injection — preferred for testability.
@Service
public class UserService {
private final UserRepository userRepository;
public UserService(UserRepository userRepository) {
this.userRepository = userRepository;
}
}
- Using setters — less common but possible.
Spring Boot automatically scans components marked with @Component, @Service, @Repository and creates their instances, wiring dependencies.
You can also use @Qualifier to select specific implementations if there are multiple.