Modes of Wiring (Dependency Injection) Supported by Spring Container (SC)
1. Explicit Wiring
The programmer explicitly specifies dependencies using Java code (setters, parameterized constructors, or factory methods) and XML configuration.
1.1 Constructor-Based Dependency Injection
- Use Case: Mandatory dependencies (dependency is created before the dependent).
- Steps:
- In the dependent bean class, define a parameterized constructor for each dependency.
- In the XML configuration file:
- Use
<constructor-arg name|type|index value|ref/>
for each dependency.
- Use
value
for injecting primitive types.
- Use
ref
for injecting dependency bean references.
1.2 Setter-Based Dependency Injection
- Use Case: Optional dependencies (dependent is created before the dependency).
- Steps:
- In the dependent bean class, provide a setter method for each dependency.
- In the XML configuration file:
- Use
<property name value|ref/>
for each dependency.
- Use
value
for injecting primitive types.
- Use
ref
for injecting dependency bean references.
1.3 Factory Method-Based Dependency Injection
- Use Case: Spring Container provides dependencies without requiring parameterized constructors or setters, using a factory method.
- Definition: A factory method is a
public static
method that returns a bean instance.
- Steps:
- Define a factory method in the bean class.
- In the XML configuration file:
- Add
factory-method="nameOfFactoryMethod"
attribute in the <bean>
tag.
- To supply arguments to the factory method, use
<constructor-arg name|type|index value|ref/>
.
2. Autowiring (Implicit Wiring)
Autowiring allows the Spring Container to automatically resolve and inject dependencies. Configured using the autowire
attribute in the <bean>
tag:
<bean ... autowire="no|byName|byType|constructor"/>
- Default value:
autowire="no"
(no autowiring, explicit wiring required).
2.1 Autowire="byName" or "byType"