Sobes.tech
Junior — Middle

Can you explain the purpose and working principle of the @Autowired annotation in the Spring Framework?

sobes.tech AI

Answer from AI

The @Autowired annotation in Spring Framework is used for automatic dependency injection. It allows Spring to automatically find and inject the required bean (component) into a field, constructor, or setter of a class.

How it works:

  • Spring scans the application context and creates beans.
  • When it encounters @Autowired, Spring searches for a suitable bean by type.
  • If a bean is found, it is automatically injected into the annotated field or constructor.
  • If there are multiple beans of the same type, @Qualifier can be used for clarification.

Example:

@Component
public class UserService {
    @Autowired
    private UserRepository userRepository;
    // ...
}

Thus, @Autowired simplifies dependency management and promotes inversion of control (IoC), making the code more modular and testable.