1. Create a java or web project. When I create a web project, myeclipse2013 is used by the compiler.
2. Add the following core packages required by spring under the lib directory:
You also need to import the driver package of the database under the lib directory. If you want to do web development, you also need to import the driver package to the buiderpath. Otherwise, the driver package may not be found.
3. Compile the spring configuration file appliactionContext. xml under the src directory. The format of applicationContext. xml is in the official spring document. My configuration file is as follows:
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.xsd>
4. Compile the test class
1. Write interfaces;
Package com. face;
Public interface Human {
Public void eat ();
Public void walk ();
}
2. Implementation class
Package com. iface;
Import com. face. Human;
Public class American implements Human {
@ Override
Public void eat (){
// TODO Auto-generated method stub
System. out. println ("American food! ");
}
@ Override
Public void walk (){
// TODO Auto-generated method stub
System. out. println ("Americans often take a bus! ");
}
}
Package com. iface;
Import com. face. Human;
Public class Chinese implements Human {
@ Override
Public void eat (){
// TODO Auto-generated method stub
System. out. println ("Chinese will eat it! ");
}
@ Override
Public void walk (){
// TODO Auto-generated method stub
System. out. println ("Chinese are walking fast! ");
}
}
3. Write Factory
Package com. factory;
Import com. face. Human;
Import com. iface. American;
Import com. iface. Chinese;
Public class Factory {
Public Human getHuman (String name ){
If ("Chinese". equals (name )){
Return new Chinese ();
} Else if ("American". equals (name )){
Return new American ();
} Else {
Return null;
}
}
}
5. Compile the test class
Package com. test;
Import org. springframework. context. ApplicationContext;
Import org. springframework. context. support. ClassPathXmlApplicationContext;
Import org. springframework. context. support. FileSystemXmlApplicationContext;
Import com. face. Human;
Public class TestMain1 {
/**
* @ Param args
*/
Public static void main (String [] args ){
// TODO Auto-generated method stub
ApplicationContext context =
New FileSystemXmlApplicationContext ("src/applicationContext. xml ");
Human human = null;
Human = (Human) context. getBean ("chinese ");
Human. eat ();
Human. walk ();
Human = (Human) context. getBean ("american ");
Human. eat ();
Human. walk ();
}
}
6. Test result output:
Chinese will eat it!
Chinese are walking fast!
Western food for Americans!
Americans often take a bus!