Example of dependency injection in Spring (USB devices and smart devices)

Source: Internet
Author: User

1, first write interface

Interface SmartDevice//Smart Device interface
{

public void SaveData (String data); Save Data side
Method

}

Interface USB//USB Interface
{
public void Insert ();
Public String read ();
public void Write (String s);
public void pop ();


}

2, and then build a specific class

public class computer implements SmartDevice
{
Private USB Usbdevice;
Public computer () {}//cannot construct USB device here
public void SaveData (String data)//Implement Smart setting
Method of Preparation
{
Insert,write,pop
}
Assembling a USB device to a computer
public void Setusbdevice (USB u) {usbdevice=u;}
}

public class Udisk implements USB//u disk
{

public void Insert () {...}
Public String Read () {...}
public void Write (String s) {...}
public void Pop () {...}

}

3. Final configuration

<?xml version= "1.0" encoding= "UTF-8"?>
<beans
Xmlns= "Http://www.springframework.org/schema/beans"
Xmlns:xsi= "Http://www.w3.org/2001/XMLSchema-instance"
xmlns:p= "http://www.springframework.org/schema/p"
xsi:schemalocation= "Http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/ Spring-beans-3.0.xsd ">


<bean id= "theudisk" class= "com. Udisk "abstract=" false "
lazy-init= "Default" autowire= "Default" >
</bean>
<bean id= "Thecomputer" class= "Com.computer" abstract= "false"
lazy-init= "Default" autowire= "Default"
>
<property name= "Usbdevice" ref= "Theudisk"/>
</bean></beans>

4. Main function call

public class Test {
public static void Main (string[] args) {

ApplicationContext ApplicationContext = new Classpathxmlapplicationcontext (
New string[] {"Beans.xml", "Applicationcontext.xml"});
Computer C = (computer) Applicationcontext.getbean ("Thecomputer");
C.savedata ("personal resume");
}

}

Example of dependency injection in Spring (USB devices and smart devices)

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.