Junior — Middle
Can you explain the purpose of the @Inject annotation in the context of dependency injection?
sobes.tech AI
Answer from AI
The @Inject annotation is used in Java to indicate the point where a dependent object should be injected. It is a key element in dependency injection (DI) mechanisms, allowing the DI container to automatically create and pass the required dependencies into class fields, constructors, or methods.
For example, if a class depends on another service, annotating a field or constructor with @Inject tells the framework to provide an instance of that service when creating the object:
public class UserService {
@Inject
private UserRepository userRepository;
// or through constructor
@Inject
public UserService(UserRepository userRepository) {
this.userRepository = userRepository;
}
}
Thus, @Inject simplifies dependency management and promotes loose coupling of components.