Spring Dependency Injection via setter method
In the previous example we have
seen what is dependency injection and what all types of dependency injection spring supports. This page gives an idea about how to achieve
dependency injection via setter method. Dependency injection via setter method is very simple.
Here is a simple interface, which prints colors:
package com.java2novice.bean;
public interface MyColor {
public void printColor();
}
|
An implementation class for above interface:
package com.java2novice.bean;
public class BlueColor implements MyColor {
@Override
public void printColor() {
System.out.println("It is blue in color...");
}
}
|
Here is ColorManager, we are using dependency injection via setter method in this class:
package com.java2novice.bean;
public class ColorManager {
MyColor color;
public void pringColor(){
this.color.printColor();
}
/**
* dependency injection through setter method
* @param myColor
*/
public void setMyColor(MyColor myColor){
this.color = myColor;
}
}
|
You can see spring bean configuration file below. We have two bean declarations. If you closely monitor property tag,
we are passing blueColor reference to myColor variable, which is setter method input parameter. The property tag calls ColorManager.setMyColor()
and passes the object reference of blueColor.
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd">
<bean id="colorManager" class="com.java2novice.bean.ColorManager">
<property name="myColor" ref="blueColor" />
</bean>
<bean id="blueColor" class="com.java2novice.bean.BlueColor" />
</beans>
|
Here is the dependency injection via setter method demo class:
package com.java2novice.test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import com.java2novice.bean.ColorManager;
public class DiSetterDemo {
public static void main(String a[]){
@SuppressWarnings("resource")
ApplicationContext context
= new ClassPathXmlApplicationContext("applicationContext.xml");
ColorManager clrManager = (ColorManager)context.getBean("colorManager");
clrManager.pringColor();
}
}
|
|