What are the different
types of IOC (dependency injection)
There
are three types of dependency injection:
· Constructor
Injection (e.g. Pico container, Spring etc): This will injects the dependency via a
constructor.
In the class OutputHelper IOutputGenerator
outputGenerator;
OutputHelper(IOutputGenerator outputGenerator){
this.outputGenerator = outputGenerator; }
In the xml file <bean id="OutputHelper" class="com.mkyong.output.OutputHelper">
<constructor-arg>
<bean class="com.mkyong.output.impl.CsvOutputGenerator" />
</constructor-arg>
</bean>
· Setter
Injection (e.g. Spring): This is the most popular it will injects the dependency via a
setter method.
In the class OutputHelper IOutputGenerator
outputGenerator;
public void setOutputGenerator(IOutputGenerator outputGenerator){
this.outputGenerator = outputGenerator; }
In the xml file <bean id="OutputHelper" class="com.mkyong.output.OutputHelper">
<property name="outputGenerator" ref="CsvOutputGenerator" />
</property>
</bean>
·
Interface Injection (e.g. Avalon): Injection is done through an
interface.
Note: Spring supports only Constructor and Setter Injection