Scenario: There is now a disk-output business that the client needs to output through 2 business objects. One is via floppy (floppy disk) and the other is via USB interface.
1. define an interface
For example:
Package spring.basic.BusinessFactory;
Public interface Idevicewriter {
public void Savetodevice ();
}
2. defines a class that implements an interface (overriding interface methods)
For example: (two classes that implement interfaces are defined here)
Class Floppywriter:
Package spring.basic.BusinessFactory;
public class Floppywriter implements Idevicewriter {
public void Savetodevice () {
System.out.println ("Save to Floppy disk ...");
}
}
Class Usbdiskwriter:
Package spring.basic.BusinessFactory;
public class Usbdiskwriter implements Idevicewriter {
public void Savetodevice () {
System.out.println ("Save to Mobile HDD ...");
}
}
3. Defining the Business class (specifying the functionality of the class)
Package spring.basic.BusinessFactory;
public class Businessbean {
Private Idevicewriter writer;
public void Setdevicewriter (Idevicewriter writer) {
This.writer = writer;
}
Public Idevicewriter Getdevicewriter () {
return writer;
}
public void Save () {
if (writer = = null) {
throw new RuntimeException ("Devicewriter needed ...");
}
Writer.savetodevice ();
}
}
4. Defining a configuration file (writes the class that implements the interface and the business class to the configuration file)
For example:
<?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-2.0.xsd ">
<bean id= "Floppy" class= "Spring.basic.BusinessFactory.FloppyWriter"/>
<bean id= "USB" class= "Spring.basic.BusinessFactory.UsbDiskWriter"/>
<bean id= "Businessbean"
class= "Spring.basic.BusinessFactory.BusinessBean" >
<property name= "Devicewriter" >
<ref bean= "Floppy"/>
</property>
</bean>
</beans>
5. Defining client Code
Package spring.basic.BusinessFactory;
Import Org.springframework.context.ApplicationContext;
Import Org.springframework.context.support.ClassPathXmlApplicationContext;
public class Springdemo {
public static void Main (string[] args) {
ApplicationContext context = new Classpathxmlapplicationcontext (
"Businessfactoryconfig.xml");
Businessbean business = (Businessbean) context.getbean ("Businessbean");
Business.save ();
}
}
< go > A simple description of dependency injection: