Manually wiring bean dependencies in XML or @Bean methods becomes repetitive and error-prone as the number of beans grows. Each dependency requires an explicit <property> or @Bean method parameter. Developers want the container to resolve dependencies automatically based on type or name.
Autowiring is Spring’s automatic dependency resolution mechanism. The container inspects a bean’s constructor, setter, or field and automatically provides the matching dependency. The primary modes are: byType (default with @Autowired), byName (matching bean ID to field name), and explicit @Qualifier for disambiguation.
- @Autowired field injection: Container matches field type to a bean of that type in the context
- Constructor injection (preferred): Container resolves constructor parameter types and provides matching beans
- Setter injection: Container calls the setter with the resolved dependency after instantiation
- Disambiguation: If multiple beans of the same type exist,
@Primarymarks the preferred one;@Qualifier("beanName")selects by name - Optional dependencies:
@Autowired(required=false)— if no bean is found, leaves field as null - @Resource: JSR-250 annotation, resolves by bean name (field name) first, then by type
- Mode byType: Default behavior — Spring matches by field/constructor parameter type
- Mode byName: Matches field name to bean ID (used with
@Resource) - @Primary: Marks a bean as the preferred choice when multiple candidates exist
- @Qualifier: Selects a specific bean by name when type alone is ambiguous
- Constructor injection preferred: Immutable dependencies, required by default, better testability
- Field injection: Simplest but makes testing harder (no way to set field without reflection)
- Built from: Spring IoC Container — Autowiring is the DI resolution mechanism within the container
- Built from: Spring Framework — Autowiring is a core Spring DI feature
- Related: Spring Bean Lifecycle — Autowiring executes during the dependency injection phase
- Related: Spring Annotations — @Autowired, @Qualifier, @Primary are Spring annotations
- Contrasts with: EJB Context — EJB’s JNDI lookup is explicit; Spring autowiring is implicit
- NoUniqueBeanDefinitionException: Multiple beans of same type without @Primary or @Qualifier — the most common autowiring error
- Field injection in unit tests: Need reflection or Spring test runner; constructor injection avoids this entirely
- Circular dependency with constructor injection: Unresolvable — use @Lazy on one side or switch to setter injection
- @Autowired on final fields: Fails because Spring uses reflection to set fields but final fields can’t be set via reflection after construction