Spring relies on injection (DI) in three ways, respectively:
1. Interface Injection
2. Setter Method Injection
3. Construct Method Injection
<?xml:namespace prefix = o ns = "Urn:schemas-microsoft-com:office:office"/>
Here's how these three dependency injections are implemented in spring.
First we need the following classes:
Interface Logic.java
Interface Implementation Class Logicimpl.java
A processing class Loginaction.java
There is also a test class Testmain.java
Logic.java as follows:
Package com.spring.test.di;
Public Interface Logic {
Public String GetName ();
}
Logicimpl.java as follows:
Package com.spring.test.di;
Public class Logicimpl implements logic{
Public String GetName () {
return "Fengyun";
}
}
Testmain.java
Package com.spring.test.di;
Import Org.springframework.context.ApplicationContext;
Import Org.springframework.context.support.FileSystemXmlApplicationContext;
public class Testmain {
/**
* @param args
*/
public static void Main (string[] args) {
Get ApplicationContext Object
ApplicationContext CTX = new Filesystemxmlapplicationcontext (
"Applicationcontext.xml");
Get Bean
Loginaction loginaction = (loginaction) ctx.getbean ("Loginaction");
Loginaction.execute ();
}
}
Loginaction.java will vary slightly depending on the injection method used
The following method is injected to see the Loginaction.java class
Setter Method Injection:
Package com.spring.test.di;
Public class loginaction {
Private Logic logic;
Public void Execute () {
String name = Logic.getname ();
System.out.print ("My name is" + name);
}
/**
* @return The logic
*/
Public Logic Getlogic () {
return logic;
}
/**
* @param logic
* The logic to set
*/
Public void setlogic (logic logic) {
this. Logic = logic;
}
}