Junior — Middle
Explain the concept of dependency injection in Spring and how it is implemented
sobes.tech AI
Answer from AI
Dependency Injection (DI) in Spring is a way of managing object dependencies, where the Spring container is responsible for creating and wiring objects, rather than the object itself creating or searching for its dependencies.
Main methods of implementing DI in Spring:
- Through constructor — dependencies are passed via constructor parameters.
- Through setters — dependencies are set via setter methods.
- Through fields annotated with @Autowired — Spring automatically injects the required beans.
Example of injection via annotation:
@Component
public class UserService {
private final UserRepository userRepository;
@Autowired
public UserService(UserRepository userRepository) {
this.userRepository = userRepository;
}
}
Here, Spring will automatically create an instance of UserRepository and pass it to the UserService constructor. This makes it easy to change dependency implementations, simplifies testing, and increases code modularity.