Sobes.tech
Junior — Middle

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:

  1. Annotations: Use annotations like @Component, @Service, @Repository to designate classes as beans, and @Autowired for automatic dependency injection.

  2. XML Configuration: In older projects, beans are described in XML files, specifying the class and dependencies.

  3. Java Configuration: Use classes annotated with @Configuration and methods with @Bean to 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.

How can objects be instantiated and managed within… - sobes.tech