Hints
DI is dependency Injection. Spring supports DI to injecting beans in loosly coupled manner.
In below example Player is a definition class. PlayerDAO is a interface which is used in other Robot class. Player is not coupled anywhere tightly.
|
Download App as Zip
Spring dependency injection example
Hints
Goto File menu then Click on Download
|
Step.1 Start a Java Project with Spring Jars
-
Open Eclipse
-
Click on menu New -> Others
-
In wizards type "Java Project" and Select "Java Project"
-
Click Next
-
Enter project name as "SpringDependencyInjectionExample", then click Next
-
Goto Libraries tab, then click on Add External JARs, then select Spring's 21 Framework Jars and commons-logging-1.1.jar.
-
Click Finish.
|
Step.2 Project Explorer Preview
|
package com.springexamples;
public interface PlayerDAO {
public void playerDetails();
public String getPlayerName();
public int getPlayerAge();
}
|
package com.springexamples;
public class Player implements PlayerDAO {
private String playerName;
private int playerAge;
public Player(String playerName,int playerAge){
this.playerName = playerName;
this.playerAge = playerAge;
}
public String getPlayerName() {
return playerName;
}
public void setPlayerName(String playerName) {
this.playerName = playerName;
}
public int getPlayerAge() {
return playerAge;
}
public void setPlayerAge(int playerAge) {
this.playerAge = playerAge;
}
public void playerDetails(){
System.out.println("Player Details\n");
System.out.println("Name: "+this.playerName);
System.out.println("Age: "+this.playerAge);
}
}
|
package com.springexamples;
public class Robot {
private PlayerDAO player;
public Robot(PlayerDAO player){
this.player = player;
}
public void sayHello(){
System.out.println("Robot Saying, Hi, "+player.getPlayerName()+"("+player.getPlayerAge()+")");
}
public void sayBye(){
System.out.println("Robot Saying, Bye, "+player.getPlayerName()+"("+player.getPlayerAge()+")");
}
}
|
<?xml version="1.0" encoding="UTF-8"?>
<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="john" class="com.springexamples.Player">
<constructor-arg value="John Peter" />
<constructor-arg value="29" />
</bean>
<bean id="johnPlayer" class="com.springexamples.Robot">
<constructor-arg ref="john" />
</bean>
</beans>
|
package com.springexamples;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class RunMyProgram {
public static void main(String[] args) {
ApplicationContext context = new ClassPathXmlApplicationContext("bean.xml");
Robot player = (Robot) context.getBean("johnPlayer");
player.sayHello();
player.sayBye();
}
}
|
Output
Robot Saying, Hi, John Peter(29)
Robot Saying, Bye, John Peter(29)
|