Spring DI types
Dependency Injection has been present for long time in Spring. The purpose of DI is to inject the dependent objects to the application code. Thus whenever a new object is required, instead of using the new operator, Spring’s ApplicationContext is used to get it. This way the application needn’t worry about managing the objects on its own.
In Spring framework, Inversion of Control (IoC) can be achieved in three ways as described below:
Constructor Dependency Injection : In this type of DI, the bean objects are injected as constructor arguments. The syntax for adding constructor DI in Spring config file is:
<constructor-arg index="0" value="15"></constructor-arg>
As you would have noticed that an index position can be specified to inform the context which argument shall be assigned the value “15″.
Setter Dependency Injection : The setter methods are used to initialize the member variables of a bean class. The Spring framework can be used to inject values to these setter methods by using the following code in Spring config file:
<property name="country" value="India"></property>
Interface Dependency Injection : Interface injection means that DI will take place only when a bean class implements a specific interface. Spring doesn’t support interface DI out of the box. Some workaround by using @AutoWired annotation can be used to achieve the same.
Out of the above three, the Constructor and Setter injection is most used. The right kind of dependency injection to be used depends upon the requirement, If some object is to be used across multiple methods in target class then it is better to use setter DI as it will set a member variable. A good example of candidate for setter DI is DAO object which any class needs for database interaction.
An eclipse based Spring project demonstrating the constructor, setter and interface injection can be downloaded from following link: