How can objects be instantiated and managed within dependency injection when using Spring?
sobes.tech AI
Answer from AI
In Spring, objects are created and managed by the IoC (Inversion of Control) container through the Dependency Injection mechanism. The main ways to instantiate and manage objects:
-
Annotations: Use annotations like
@Component,@Service,@Repositoryto designate classes as beans, and@Autowiredfor automatic dependency injection. -
XML Configuration: In older projects, beans are described in XML files, specifying the class and dependencies.
-
Java Configuration: Use classes annotated with
@Configurationand methods with@Beanto create and configure beans.
The Spring container manages the lifecycle of objects, creating them at application startup or on demand (singleton, prototype, and other scopes).
Example with annotations:
@Component
public class UserService {
private final UserRepository userRepository;
@Autowired
public UserService(UserRepository userRepository) {
this.userRepository = userRepository;
}
// methods
}
Here, Spring will automatically create and inject UserRepository into UserService.
Thus, Spring takes care of creating and managing objects, allowing developers to focus on logic rather than manual dependency creation.