Spring interview questions
Table of Contents
How does @Autowired work?
At a high level, @Autowired is part of Spring's dependency injection mechanism. Its job is to tell Spring that a class depends on another object, and that Spring should automatically provide that dependency at runtime instead of the developer manually creating it.
During startup, Spring performs a component scan over the configured packages. It looks for classes annotated with @Component, @Service, @Repository, and @Controller. Each of these annotations signals to Spring that the class should be managed by the framework.
For every discovered component, Spring creates an object called a bean and stores it inside the ApplicationContext. You can think of the ApplicationContext as a container that holds all fully-initialized, ready-to-use objects that Spring manages for the application.
When Spring encounters the @Autowired annotation, such as on a field, constructor, or setter, it recognizes that the current bean has a dependency that needs to be satisfied. For example, if Spring sees a field of type UserService annotated with @Autowired, it understands that this class requires a UserService instance.
Rather than creating a new object itself, Spring searches inside the ApplicationContext for an existing bean that matches the required type. Spring always resolves dependencies by type first. If there is exactly one matching bean, Spring injects it automatically. If there are multiple beans of the same type, Spring then attempts to disambiguate by name or additional metadata, such as @Qualifier. If Spring cannot uniquely determine which bean to inject, it fails fast and throws an error to prevent ambiguous behavior.
Once the correct bean is identified, Spring performs the injection. The preferred and recommended approach is constructor injection, because it makes dependencies explicit and ensures the object is always created in a valid state. Field injection and setter injection are also supported, but they are generally considered less explicit and harder to test.
In essence, @Autowired allows Spring to take a fully managed object from its container and seamlessly plug it into another object that depends on it. This decouples object creation from object usage, making applications easier to maintain, test, and extend.