spring IOC核心原理

下面來了解一下Spring究竟是怎麼運行的。html

 

Java代碼 
public static void main(String[] args) {   
        ApplicationContext context = new FileSystemXmlApplicationContext(   
                "applicationContext.xml");   
        Animal animal = (Animal) context.getBean("animal");   
        animal.say();   
    }  

 

這段代碼你必定很熟悉吧,不過仍是讓咱們分析一下它吧,首先是applicationContext.xmljava

Java代碼 
<bean id="animal" class="phz.springframework.test.Cat">   
        <property name="name" value="kitty" />   
    </bean> 

他有一個類phz.springframework.test.Catspring

Java代碼 
public class Cat implements Animal {   
    private String name;   
    public void say() {   
        System.out.println("I am " + name + "!");   
    }   
    public void setName(String name) {   
        this.name = name;   
    }   
}  

 

實現了phz.springframework.test.Animal接口app

Java代碼 
public interface Animal {   
    public void say();   
}  

   

很明顯上面的代碼輸出I am kitty! 

那麼到底Spring是如何作到的呢? 
接下來就讓咱們本身寫個Spring 來看看Spring 究竟是怎麼運行的吧! 

首先,咱們定義一個Bean類,這個類用來存放一個Bean擁有的屬性this

Java代碼 
/* Bean Id */  
    private String id;   
    /* Bean Class */  
    private String type;   
    /* Bean Property */  
    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配置能夠像下面的spa

Java代碼 
<bean id="test" class="Test">   
        <property name="testMap">   
            <map>   
                <entry key="a">   
                    <value>1</value>   
                </entry>   
                <entry key="b">   
                    <value>2</value>   
                </entry>   
            </map>   
        </property>   
    </bean>  

  

 

Spring是怎樣保存上面的配置呢?,代碼以下:.net

Java代碼 
if (beanProperty.element("map") != null) {   
                    Map<String, Object> propertiesMap = new HashMap<String, Object>();   
                    Element propertiesListMap = (Element) beanProperty   
                            .elements().get(0);   
                    Iterator<?> propertiesIterator = propertiesListMap   
                            .elements().iterator();   
                    while (propertiesIterator.hasNext()) {   
                        Element vet = (Element) propertiesIterator.next();   
                        if (vet.getName().equals("entry")) {   
                            String key = vet.attributeValue("key");   
                            Iterator<?> valuesIterator = vet.elements()   
                                    .iterator();   
                            while (valuesIterator.hasNext()) {   
                                Element value = (Element) valuesIterator.next();   
                                if (value.getName().equals("value")) {   
                                    propertiesMap.put(key, value.getText());   
                                }   
                                if (value.getName().equals("ref")) {   
                                    propertiesMap.put(key, new String[] { value   
                                            .attributeValue("bean") });   
                                }   
                            }   
                        }   
                    }   
                    bean.getProperties().put(name, propertiesMap);   
                }  

  

接下來就進入最核心部分了,讓咱們看看Spring 究竟是怎麼依賴注入的吧,其實依賴注入的思想也很簡單,它是經過反射機制實現的,在實例化一個類時,它經過反射調用類中set方法將事先保存在HashMap中的類屬性注入到類中。讓咱們看看具體它是怎麼作的吧。 
首先實例化一個類,像這樣xml

Java代碼 
public static Object newInstance(String className) {   
        Class<?> cls = null;   
        Object obj = null;   
        try {   
            cls = Class.forName(className);   
            obj = cls.newInstance();   
        } catch (ClassNotFoundException e) {   
            throw new RuntimeException(e);   
        } catch (InstantiationException e) {   
            throw new RuntimeException(e);   
        } catch (IllegalAccessException e) {   
            throw new RuntimeException(e);   
        }   
        return obj;   
    }  

  

接着它將這個類的依賴注入進去,像這樣htm

Java代碼 
public static void setProperty(Object obj, String name, String value) {   
        Class<? extends Object> clazz = obj.getClass();   
        try {   
            String methodName = returnSetMthodName(name);   
            Method[] ms = clazz.getMethods();   
            for (Method m : ms) {   
                if (m.getName().equals(methodName)) {   
                    if (m.getParameterTypes().length == 1) {   
                        Class<?> clazzParameterType = m.getParameterTypes()[0];   
                        setFieldValue(clazzParameterType.getName(), value, m,   
                                obj);   
                        break;   
                    }   
                }   
            }   
        } catch (SecurityException e) {   
            throw new RuntimeException(e);   
        } catch (IllegalArgumentException e) {   
            throw new RuntimeException(e);   
        } catch (IllegalAccessException e) {   
            throw new RuntimeException(e);   
        } catch (InvocationTargetException e) {   
            throw new RuntimeException(e);   
        }   
}  

  

最後它將這個類的實例返回給咱們,咱們就能夠用了。咱們仍是以Map爲例看看它是怎麼作的,我寫的代碼裏面是建立一個HashMap並把該HashMap注入到須要注入的類中,像這樣,blog

Java代碼 
if (value instanceof Map) {   
                Iterator<?> entryIterator = ((Map<?, ?>) value).entrySet()   
                        .iterator();   
                Map<String, Object> map = new HashMap<String, Object>();   
                while (entryIterator.hasNext()) {   
                    Entry<?, ?> entryMap = (Entry<?, ?>) entryIterator.next();   
                    if (entryMap.getValue() instanceof String[]) {   
                        map.put((String) entryMap.getKey(),   
                                getBean(((String[]) entryMap.getValue())[0]));   
                    }   
                }   
                BeanProcesser.setProperty(obj, property, map);   
            }  

  

好了,這樣咱們就能夠用Spring 給咱們建立的類了,是否是也不是很難啊?固然Spring能作到的遠不止這些,這個示例程序僅僅提供了Spring最核心的依賴注入功能中的一部分。 

轉載:http://blog.csdn.net/it_man/article/details/4402245

相關文章
相關標籤/搜索