Dependency Injection technology in the spring framework

Source: Internet
Author: User

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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.