Spring Bean Autowiring

Spring bean autowiring

Autowiring in Spring is a feature that enables the framework to automatically find and inject dependent beans into a target bean's properties, without needing manual configuration. This simplifies development, especially in large applications with many dependencies between objects. When autowiring is used, Spring searches the container for beans of the required type and injects them into the dependent object automatically.

We use the `@Autowired` annotation to tell the Spring container to automatically inject dependent beans into a target bean's properties. It enables autowiring for specific properties, allowing Spring to resolve dependencies and create the required objects without manual configuration.

Where can we use @Autowired Annotation?

We can use the @Autowired annotation at constructor level, field level, setter method level, and normal method level.


No wiring inside spring


Various Ways of wiring beans in Spring

1. Using Method Call


2. Using Method Parameters


3. Using @Autowired on class fields


4. Using @Autowired on setter method


5. Using @Autowired with constructor

What is the Ambiguity Problem with @Autowired?

When using @Autowired, ambiguity can arise if multiple beans of the same type are present in the Spring container. Spring won’t know which bean to inject, leading to errors such as NoUniqueBeanDefinitionException. This happens because @Autowired by default tries to inject by type, and having multiple beans of the same type creates confusion for the framework.



Solution 1 : matching method name (Its no longer supported)


Solution 2 : @Primary


Solution 3 : @Qualifier