Accounting for 134 (experimental Class) Zhou Luling
Dependency injection is achieved through a tightly coupled relationship between the computer class and the USB class.
Create a USB class
Public interface USB//USB interface
{
public void Insert ();//Insert
Public String read ();//Read
public void Write (String s);//write
public void Pop ();//Popup
}
Create an object (Bean) with the following code:
public class Udisk implements USB
{
public void Insert () {
SYSTEM.OUT.PRINTLN ("Insert USB stick");};
Public String Read () {
SYSTEM.OUT.PRINTLN ("read Data");
Return "some data";
};
public void Write (String s) {
System.out.println ("Write Data:" +s);
};
public void Pop () {
SYSTEM.OUT.PRINTLN ("Eject USB flash drive");
};
}
Create an object (Bean) with the following code:
Public interface SmartDevice {
public void SaveData (String data);
}
Create the computer class with the following code:
public class computer implements SmartDevice
{
Private USB Usbdevice;
Public computer () {}//This device cannot construct USB
public void SaveData (String data)//method for implementing smart devices
{
Usbdevice.insert ();
Usbdevice.write (data);
Usbdevice.pop ();
}
public void Setusbdevice (USB u)
{
Usbdevice=u;
}
}
In modifying the configuration file Applicationcontext.xml, instantiate the bean with the following code:
<bean id= "Theudisk" class= "Com.cqvie.UDisk" abstract= "false"
lazy-init= "Default" autowire= "Default" >
</bean>
<bean id= "Thecomputer" class= "Com.cqvie.Computer" abstract= "false"
lazy-init= "Default" autowire= "Default"
p:usbdevice-ref= "Theudisk" >
</bean>
Finally test the class, get the injected bean, the code is as follows:
public class Test {
public static void Main (string[] args)
{
ApplicationContext context=new classpathxmlapplicationcontext ("Applicationcontext.xml");
Computer c= (computer) Context.getbean ("Thecomputer");
C.savedata ("Success");
}
}
Dependency Injection technology in the spring framework