In general, IOC is intended for interface programming.
1. Define two interfaces. The class is as follows:
Package com. svse. Spring. IOC;
// Ink type
Public interface ink {
Public String getcolor ();
}
// Paper type
Package com. svse. Spring. IOC;
Public interface paper {
Public String getsize ();
}
Their specific implementation classes are as follows:
// Blue ink
Package com. svse. Spring. IOC;
Public class blueink implements ink {
Public String getcolor (){
Return "blue ";
}
}
// Red ink
Package com. svse. Spring. IOC;
Public class redink implements ink {
Public String getcolor (){
Return "red ";
}
}
// A4 paper
Package com. svse. Spring. IOC;
Public class A4 implements paper {
Public String getsize (){
Return "A4 ";
}
}
// A5 paper
Package com. svse. Spring. IOC;
Public class A5 implements paper {
Public String getsize (){
Return "A5 ";
}
}
// A6 paper
Package com. svse. Spring. IOC;
Public class A6 implements paper {
Public String getsize (){
Return "A6 ";
}
}
2. What kind of ink and paper printing are used:
Package com. svse. Spring. IOC;
Public class printer {
Private ink = NULL;
Private paper = NULL;
Public ink getink (){
Return ink;
}
Public void setink (ink ){
This. Ink = ink;
}
Public paper getpaper (){
Return paper;
}
Public void setpaper (Paper paper ){
This. Paper = paper;
}
Public void print (string content)
{
System. Out. println ("[" + ink. getcolor () + "]" + "[" + paper. getsize () + "]" + content );
}
}
3, add spring-core.jar, spring-beans.jar, spring-context.jar package in the project
Assemble the specific implementation classes in the applicationcontext. xml file:
<? XML version = "1.0" encoding = "UTF-8"?>
<! Doctype beans public "-// spring // DTD bean // en" "http://www.springframework.org/dtd/spring-beans.dtd">
<Beans>
<! -- Define paper -->
<Bean id = "A4" class = "com. svse. Spring. IOC. A4"> </bean>
<Bean id = "A5" class = "com. svse. Spring. IOC. A5"> </bean>
<Bean id = "A6" class = "com. svse. Spring. IOC. A6"> </bean>
<! -- Define ink cartridges -->
<Bean id = "redink" class = "com. svse. Spring. IOC. redink"> </bean>
<Bean id = "blueink" class = "com. svse. Spring. IOC. blueink"> </bean>
<! -- Define a printer (assemble a printer) -->
<Bean id = "Printer" class = "com. svse. Spring. IOC. Printer">
<Property name = "ink" ref = "blueink"> </property>
<Property name = "paper" ref = "A6"> </property>
</Bean>
</Beans>
4. Test IOC
Package com. svse. Spring. IOC;
Import org. springframework. Context. applicationcontext;
Import org. springframework. Context. Support. classpathxmlapplicationcontext;
Public class iocmain {
/**
* @ Test
*/
Public static void main (string [] ARGs ){
Applicationcontext context =
New classpathxmlapplicationcontext ("applicationcontext. xml ");
Printer printer = (printer) Context. getbean ("Printer ");
Printer. Print ("Welcome 2 Spring framework .");
}
}