首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 软件管理 > 软件架构设计 >

Spring的容易应用实例

2012-10-16 
Spring的简单应用实例Spring的简单应用实例 先定义一个接口human,1. public interface human{2.void eat()

Spring的简单应用实例
Spring的简单应用实例



先定义一个接口human,

   1. public interface human{   2.     void eat();   3.     void walk();   4. } 


然后写出实现这个接口的两个子类Chinese和American类
   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. } 


然后创建一个工厂类factory,以实现工厂模式
   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. }

这就是java的工厂模式

下面介绍一下java spring的IoC(控制翻转inversion of control)模式

在项目根目录下创建一个beam.xml文件
   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.

从这个程序可以看到,ctx就相当于原来的Factory工厂,原来的Factory就可以删除掉了。然后又把Factory里的变量移到了ClientTest类里,整个程序结构基本一样。

也许有人说,IoC和工厂模式不是一样的作用吗,用IoC好象还麻烦一点。
       举个例子,如果用户需求发生变化,要把Chinese类修改一下。那么前一种工厂模式,就要更改Factory类的方法,并且重新编译布署。而IoC只需要将class属性改变一下,并且由于IoC利用了Java反射机制,这些对象是动态生成的,这时我们就可以热插拨Chinese对象

关于IoC的低侵入性。
什么是低侵入性?如果你用过Struts或EJB就会发现,要继承一些接口或类,才能利用它们的框架开发。这样,系统就被绑定在Struts、EJB上了,对系统的可移植性产生不利的影响。如果代码中很少涉及某一个框架的代码,那么这个框架就可以称做是一个低侵入性的框架。
Spring的侵入性很低,Humen.java、Chinese.java等几个类都不必继承什么接口或类。但在ClientTest里还是有一些Spring的影子:FileSystemXmlApplicationContext类和ctx.getBean方式等。
现在,低侵入性似乎也成了判定一个框架的实现技术好坏的标准之一

热点排行