Autowiring in Spring
Autowiring is Spring's way of automatically resolving dependencies without explicit configuration. It's like a smart assistant that knows what your object needs and supplies it.
Spring offers several autowiring modes (in XML):
no, byName, byType, constructor. But in modern Spring, we use @Autowired annotation.@Autowired can be applied to:
- Constructor
- Setter
- Field
- Arbitrary methods
Spring tries to match by type. If multiple beans of the same type exist, you can use
@Qualifier to specify which one.@Component
public class Car {
@Autowired
private Engine engine; // field injection
public void drive() {
engine.start();
}
}
@Component
public class Engine {
public void start() {
System.out.println("Engine started");
}
}
If you have two Engine implementations:
@Component("petrolEngine")
public class PetrolEngine implements Engine { ... }
@Component("dieselEngine")
public class DieselEngine implements Engine { ... }
@Component
public class Car {
@Autowired
@Qualifier("dieselEngine")
private Engine engine;
}
Two Minute Drill
- Autowiring lets Spring inject dependencies automatically.
- Use
@Autowiredon fields, setters, or constructors. - Spring wires by type; use
@Qualifierto resolve ambiguity. - Autowiring reduces explicit bean references in configuration.
Need more clarification?
Drop us an email at career@quipoinfotech.com
