通过实例浅谈Spring运作机制

开发 后端
笔者写这篇文章只是想让大家了解一下的Spring运作机制,并不是想重造轮子噢,希望大家看完这篇文章后能对Spring运作机制有更深入的了解,希望这篇文章对你有所帮助喔!

看到这个标题大家可能又想:哎,又一个重新发明轮子的人。在这里很想先声明一下,写这篇文章只是想让大家了解一下Spring到底是怎么运行的,并不是想重造轮子噢,希望大家看完这篇文章后能对Spring运作机制有更深入的了解,希望这篇文章对你有所帮助喔!好,言归正传,让我们来一起探索吧!

我们先从最常见的例子开始吧

Java代码

  1. public static void main(String[] args) {     
  2.         ApplicationContext context = new FileSystemXmlApplicationContext(     
  3.                 "applicationContext.xml");     
  4.         Animal animal = (Animal) context.getBean("animal");     
  5.         animal.say();     
  6.     }    
  7.  
  8. public static void main(String[] args) {  
  9.   ApplicationContext context = new FileSystemXmlApplicationContext(  
  10.     "applicationContext.xml");  
  11.   Animal animal = (Animal) context.getBean("animal");  
  12.   animal.say();  
  13.  } 

这段代码你一定很熟悉吧,不过还是让我们分析一下它吧,首先是applicationContext.xml

Java代码

  1. <bean id="animal" class="phz.springframework.test.Cat">     
  2.         <property name="name">     
  3.             <value>kitty</value>     
  4.         </property>     
  5. </bean>    
  6.  
  7. <bean id="animal" class="phz.springframework.test.Cat"> 
  8.   <property name="name"> 
  9.    <value>kitty</value> 
  10.   </property> 
  11. </bean> 

他有一个类phz.springframework.test.Cat =

Java代码

  1. public class Cat implements Animal {     
  2.     private String name;     
  3.     public void say() {     
  4.         System.out.println("I am " + name + "!");     
  5.     }     
  6.     public void setName(String name) {     
  7.         this.name = name;     
  8.     }     
  9. }    
  10.  
  11. public class Cat implements Animal {  
  12.  private String name;  
  13.  public void say() {  
  14.   System.out.println("I am " + name + "!");  
  15.  }  
  16.  public void setName(String name) {  
  17.   this.name = name;  
  18.  }  

实现了phz.springframework.test.Animal接口

Java代码

  1. public interface Animal {     
  2.     public void say();     
  3. }    
  4.  
  5. public interface Animal {  
  6.  public void say();  

很明显上面的代码输出I am kitty!

那么到底Spring是如何做到的呢?

接下来就让我们自己写个Spring 来看看Spring运作机制吧!

首先,我们定义一个Bean类,这个类用来存放一个Bean拥有的属性

Java代码

  1. /* Bean Id */    
  2.     private String id;     
  3.     /* Bean Class */    
  4.     private String type;     
  5.     /* Bean Property */    
  6.     private Map<String, Object> properties = new HashMap<String, Object>();    
  7.  
  8. /* Bean Id */  
  9.  private String id;  
  10.  /* Bean Class */  
  11.  private String type;  
  12.  /* Bean Property */  
  13.  private Map<String, Object> properties = new HashMap<String, Object>(); 

一个Bean包括id,type,和Properties。

接下来Spring 就开始加载我们的配置文件了,将我们配置的信息保存在一个HashMap中,HashMap的key就是Bean 的 Id ,HasMap 的value是这个Bean,只有这样我们才能通过context.getBean("animal")这个方法获得Animal这个类。我们都知道Spirng可以注入基本类型,而且可以注入像List,Map这样的类型,接下来就让我们以Map为例看看Spring是怎么保存的吧

Map配置可以像下面的

Java代码

  1. <bean id="test" class="Test">     
  2.         <property name="testMap">     
  3.             <map>     
  4.                 <entry key="a">     
  5.                     <value>1</value>     
  6.                 </entry>     
  7.                 <entry key="b">     
  8.                     <value>2</value>     
  9.                 </entry>     
  10.             </map>     
  11.         </property>     
  12.     </bean>    
  13.  
  14. <bean id="test" class="Test"> 
  15.   <property name="testMap"> 
  16.    <map> 
  17.     <entry key="a"> 
  18.      <value>1</value> 
  19.     </entry> 
  20.     <entry key="b"> 
  21.      <value>2</value> 
  22.     </entry> 
  23.    </map> 
  24.   </property> 
  25.  </bean> 

Spring运作机制中是怎样保存上面的配置呢?,代码如下:

Java代码

  1. if (beanProperty.element("map") != null) {     
  2.                     Map<String, Object> propertiesMap = new HashMap<String, Object>();     
  3.                     Element propertiesListMap = (Element) beanProperty     
  4.                             .elements().get(0);     
  5.                     Iterator<?> propertiesIterator = propertiesListMap     
  6.                             .elements().iterator();     
  7.                     while (propertiesIterator.hasNext()) {     
  8.                         Element vet = (Element) propertiesIterator.next();     
  9.                         if (vet.getName().equals("entry")) {     
  10.                             String key = vet.attributeValue("key");     
  11.                             Iterator<?> valuesIterator = vet.elements()     
  12.                                     .iterator();     
  13.                             while (valuesIterator.hasNext()) {     
  14.                                 Element value = (Element) valuesIterator.next();     
  15.                                 if (value.getName().equals("value")) {     
  16.                                     propertiesMap.put(key, value.getText());     
  17.                                 }     
  18.                                 if (value.getName().equals("ref")) {     
  19.                                     propertiesMap.put(key, new String[] { value     
  20.                                             .attributeValue("bean") });     
  21.                                 }     
  22.                             }     
  23.                         }     
  24.                     }     
  25.                     bean.getProperties().put(name, propertiesMap);     
  26.                 }    
  27.  
  28. if (beanProperty.element("map") != null) {  
  29.      Map<String, Object> propertiesMap = new HashMap<String, Object>();  
  30.      Element propertiesListMap = (Element) beanProperty  
  31.        .elements().get(0);  
  32.      Iterator<?> propertiesIterator = propertiesListMap 
  33.        .elements().iterator();  
  34.      while (propertiesIterator.hasNext()) {  
  35.       Element vet = (Element) propertiesIterator.next();  
  36.       if (vet.getName().equals("entry")) {  
  37.        String key = vet.attributeValue("key");  
  38.        Iterator<?> valuesIterator = vet.elements()  
  39.          .iterator();  
  40.        while (valuesIterator.hasNext()) {  
  41.         Element value = (Element) valuesIterator.next();  
  42.         if (value.getName().equals("value")) {  
  43.          propertiesMap.put(key, value.getText());  
  44.         }  
  45.         if (value.getName().equals("ref")) {  
  46.          propertiesMap.put(key, new String[] { value  
  47.            .attributeValue("bean") });  
  48.         }  
  49.        }  
  50.       }  
  51.      }  
  52.      bean.getProperties().put(name, propertiesMap);  
  53.     } 

接下来就进入最核心部分了,让我们看看Spring 到底是怎么依赖注入的吧,其实依赖注入的思想也很简单,它是通过反射机制实现的,在实例化一个类时,它通过反射调用类中set方法将事先保存在HashMap中的类属性注入到类中。让我们看看具体它是怎么做的吧。

首先实例化一个类,像这样

Java代码

  1. public static Object newInstance(String className) {     
  2.         Class<?> cls = null;     
  3.         Object obj = null;     
  4.         try {     
  5.             cls = Class.forName(className);     
  6.             obj = cls.newInstance();     
  7.         } catch (ClassNotFoundException e) {     
  8.             throw new RuntimeException(e);     
  9.         } catch (InstantiationException e) {     
  10.             throw new RuntimeException(e);     
  11.         } catch (IllegalAccessException e) {     
  12.             throw new RuntimeException(e);     
  13.         }     
  14.         return obj;     
  15.     }    
  16.  
  17. public static Object newInstance(String className) {  
  18.   Class<?> cls = null;  
  19.   Object obj = null;  
  20.   try {  
  21.    cls = Class.forName(className);  
  22.    obj = cls.newInstance();  
  23.   } catch (ClassNotFoundException e) {  
  24.    throw new RuntimeException(e);  
  25.   } catch (InstantiationException e) {  
  26.    throw new RuntimeException(e);  
  27.   } catch (IllegalAccessException e) {  
  28.    throw new RuntimeException(e);  
  29.   }  
  30.   return obj;  
  31.  } 

接着它将这个类的依赖注入进去,像这样

Java代码

  1. public static void setProperty(Object obj, String name, String value) {     
  2.         Class<? extends Object> clazz = obj.getClass();     
  3.         try {     
  4.             String methodName = returnSetMthodName(name);     
  5.             Method[] ms = clazz.getMethods();     
  6.             for (Method m : ms) {     
  7.                 if (m.getName().equals(methodName)) {     
  8.                     if (m.getParameterTypes().length == 1) {     
  9.                         Class<?> clazzParameterType = m.getParameterTypes()[0];     
  10.                         setFieldValue(clazzParameterType.getName(), value, m,     
  11.                                 obj);     
  12.                         break;     
  13.                     }     
  14.                 }     
  15.             }     
  16.         } catch (SecurityException e) {     
  17.             throw new RuntimeException(e);     
  18.         } catch (IllegalArgumentException e) {     
  19.             throw new RuntimeException(e);     
  20.         } catch (IllegalAccessException e) {     
  21.             throw new RuntimeException(e);     
  22.         } catch (InvocationTargetException e) {     
  23.             throw new RuntimeException(e);     
  24.         }     
  25. }    
  26.  
  27. public static void setProperty(Object obj, String name, String value) {  
  28.   Class<? extends Object> clazz = obj.getClass();  
  29.   try {  
  30.    String methodName = returnSetMthodName(name);  
  31.    Method[] ms = clazz.getMethods();  
  32.    for (Method m : ms) {  
  33.     if (m.getName().equals(methodName)) {  
  34.      if (m.getParameterTypes().length == 1) {  
  35.       Class<?> clazzParameterType = m.getParameterTypes()[0];  
  36.       setFieldValue(clazzParameterType.getName(), value, m,  
  37.         obj);  
  38.       break;  
  39.      }  
  40.     }  
  41.    }  
  42.   } catch (SecurityException e) {  
  43.    throw new RuntimeException(e);  
  44.   } catch (IllegalArgumentException e) {  
  45.    throw new RuntimeException(e);  
  46.   } catch (IllegalAccessException e) {  
  47.    throw new RuntimeException(e);  
  48.   } catch (InvocationTargetException e) {  
  49.    throw new RuntimeException(e);  
  50.   }  

***它将这个类的实例返回给我们,我们就可以用了。我们还是以Map为例看看它是怎么做的,我写的代码里面是创建一个HashMap并把该HashMap注入到需要注入的类中,像这样,

Java代码

  1. if (value instanceof Map) {     
  2.                 Iterator<?> entryIterator = ((Map<??>) value).entrySet()     
  3.                         .iterator();     
  4.                 Map<String, Object> map = new HashMap<String, Object>();     
  5.                 while (entryIterator.hasNext()) {     
  6.                     Entry<??> entryMap = (Entry<??>) entryIterator.next();     
  7.                     if (entryMap.getValue() instanceof String[]) {     
  8.                         map.put((String) entryMap.getKey(),     
  9.                                 getBean(((String[]) entryMap.getValue())[0]));     
  10.                     }     
  11.                 }     
  12.                 BeanProcesser.setProperty(obj, property, map);     
  13.             }    
  14.  
  15. if (value instanceof Map) {  
  16.     Iterator<?> entryIterator = ((Map<??>) value).entrySet()  
  17.       .iterator();  
  18.     Map<String, Object> map = new HashMap<String, Object>();  
  19.     while (entryIterator.hasNext()) {  
  20.      Entry<??> entryMap = (Entry<??>) entryIterator.next();  
  21.      if (entryMap.getValue() instanceof String[]) {  
  22.       map.put((String) entryMap.getKey(),  
  23.         getBean(((String[]) entryMap.getValue())[0]));  
  24.      }  
  25.     }  
  26.     BeanProcesser.setProperty(obj, property, map);  
  27.    } 

好了,这样我们就可以用Spring 给我们创建的类了,是不是也不是很难啊?当然Spring能做到的远不止这些,这个示例程序仅仅提供了Spring最核心的依赖注入功能中的一部分。这也是Spring运作机制中的一部分。

本文参考了大量文章无法一一感谢,在这一起感谢,如果侵犯了你的版权深表歉意,很希望对大家有帮助!

附件中包含该山寨Spring的源码,核心只有五个类,还有一个测试程序,phz.springframework.test.AnimalSayApp,可以直接运行。

【编辑推荐】

  1. JSF和Spring的集成
  2. 在Spring中进行集成测试
  3. 比较JSF、Spring MVC、Stripes、Struts 2、Tapestry、Wicket
  4. Spring中的TopLink ServerSession
  5. Spring is coming
责任编辑:彭凡 来源: javaeye论坛
相关推荐

2009-07-24 17:22:22

CLR 4.0安全模型

2009-08-25 15:30:55

DataGrid We

2009-09-22 10:09:21

Hibernate S

2009-06-26 17:34:29

Spring入门

2013-09-09 15:06:03

2011-03-10 15:22:08

访问控制机制Java

2009-07-16 09:46:20

iBATIS Log机

2012-11-07 10:06:05

路由器VPN

2009-09-18 16:32:51

Linq委托实例化

2018-06-29 14:20:05

2017-04-26 14:15:35

浏览器缓存机制

2020-09-30 06:47:22

Kotlin机制

2013-09-29 15:11:46

Linux运维内存管理

2010-04-16 11:17:33

hints调整

2019-05-10 14:00:21

小程序运行机制前端

2022-06-09 15:35:48

深度学习AI

2019-08-15 10:17:16

Webpack运行浏览器

2011-07-26 10:46:04

HTML 5

2018-12-26 16:30:09

SQL Server内部运行机制数据库

2011-03-09 09:11:52

java反射机制
点赞
收藏

51CTO技术栈公众号