Spring的简单应用实例
Spring的简单应用实例
先定义一个接口human,
1. public interface human{ 2. void eat(); 3. void walk(); 4. }
1. public class Chinese implements Human{ 2. public void eat(){ 3. System.out.println("中国人对吃很有研究"); 4. } 5. public void walk(){ 6. System.out.println("中国人田径运动不是很强"); 7. } 8. } 9. public class American implements Human{ 10. public void eat(){ 11. System.out.println("美国人以吃面包为主"); 12. } 13. public void walk(){ 14. System.out.println("美国的田径运动比较厉害"); 15. } 16. }
1. public class factory{ 2. public Human getHuman(String name){ 3. if(name.equalsIgnoreCase(chinese)) 4. return new Chinese(); 5. else if(name.equalsIgnoreCase(American) 6. return new American(); 7. else 8. throw IllegalArgumentException("你输入的人种错误,不能创建该对象"); 9. } 10. }
1. import java.util.Scanner; 2. 3. public class ClientTest{ 4. public static void main(String[] args){ 5. 6. System.out.println("input the name of you want to create:"); 7. Scanner s=new Scanner(System.in); 8. String name=s.nextline(); 9. Human human=null; 10. human=new factory().getHuman(name); 11. human.eat(); 12. human.walk(); 13. } 14. }
1. <?xml version="1.0" encoding="UTF-8"?> 2. <!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN//EN" "http://www.springframework.org/dtd/spring-beans.dtd"> 3. <beans> 4. <bean id="Chinese" name="code"> 1. import org.springframework.context.support.FileSystemXmlApplicationContext; 2. public class ClientTest { 3. 4. public static void main(String[] args) { 5. 6. ApplicationContext ctx = new FileSystemXmlApplicationContext("bean.xml"); 7. System.out.println("..."); 8. Scanner s=new Scanner(System.in); 9. String name=s.nextline(); 10. Human human=null; 11. human=(Human)ctx.getBean(name); 12. human.eat(); 13. human.walk(); 14. } 15. }16.