【spring】1.spring ioc原理和demo
我們先做一個簡單的spring例子。
面向介面程式設計,我們先來定介面
IHelloWorld
package com.services;
public interface IHelloWorld {
public void sayHello();
}
寫一個實現類,並且宣告一個String屬性,提供set方法注入
package com.services.impl; import com.services.IHelloWorld; public class HelloWorld implements IHelloWorld { private String helloWorld; public void setHelloWorld(String helloWorld) { this.helloWorld = helloWorld; } @Override public void sayHello() { System.out.println("hello world"); } }
編寫配置檔案
<pre name="code" class="html"><?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:p="http://www.springframework.org/schema/p" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.1.xsd"> <bean id="helloWorldBean" class="com.services.impl.HelloWorld"> <property name="helloWorld"> <value>helloworld !!!</value> </property> </bean> </beans>
注意看。配置檔案的含義:
beans裡面是各種bean物件的宣告。
bean物件裡面描述了bean的資訊,裡面包括bean名稱,對應的class檔案,class檔案裡的屬性和值。
程式設計測試檔案:
package com; import org.springframework.beans.factory.support.DefaultListableBeanFactory; import org.springframework.beans.factory.xml.XmlBeanDefinitionReader; import org.springframework.core.io.ClassPathResource; import com.services.IHelloWorld; public class Test { /** * @param args */ public static void main(String[] args) { ClassPathResource resource = new ClassPathResource( "applicationContext.xml"); DefaultListableBeanFactory factory = new DefaultListableBeanFactory(); XmlBeanDefinitionReader reader = new XmlBeanDefinitionReader(factory); reader.loadBeanDefinitions(resource); IHelloWorld hello = (IHelloWorld) factory.getBean("helloWorldBean"); hello.sayHello(); } }
ioc原理簡單分析:
我們看看測試程式碼:
//這裡其實是讀取xml檔案
ClassPathResource resource = new ClassPathResource(
"applicationContext.xml");
//建立bean工廠,把讀取到的載入我們的xml的reader當中
DefaultListableBeanFactory factory = new DefaultListableBeanFactory();
XmlBeanDefinitionReader reader = new XmlBeanDefinitionReader(factory);
reader.loadBeanDefinitions(resource);
//這裡其實是通過反射,獲得bean物件
IHelloWorld hello = (IHelloWorld) factory.getBean("helloWorldBean");
hello.sayHello();
簡述ioc原理:如果我們不使用spring,那麼bean物件建立就是通過new等方式硬程式碼的方式寫入程式中。
ioc其實是把bean的資訊寫入xml檔案,通過jdom去解析到bean節點資訊,然後裡面包含bean的id或者name,還有bean對應的class全路徑,那麼我們通過getBean方法,就可以獲取到bean的類全路徑,通過反射就可以得到bean物件,程式內部其實是用hashMap來儲存xml解析出來的資訊的,hashMap的key其實就是我們寫在xml裡面的id,而值就是class對應的類全路徑,然後通過物件工廠,得到bean工廠後getBean就可以反射得到bean物件。類的建立過程是spring來幫你完成,我們自己的程式碼中並未建立物件,也沒有對屬性賦值,整個過程spring容器完成,這也就是通常所說的依賴注入,或者說叫控制反轉(建立物件的過程是spring容器完成的,控制權發生了變化)
ioc其實裡面應用到了jcom(解析xml),反射(xml裡面的類全路徑後getBean得到物件),工廠設計模式。
部分原始碼:
BeanFactory為頂層介面:該介面有很多常見的子介面和實現類,大家可能還會看到很多其他人程式碼用的XmlBeanFactory等子類實現,該介面有很多方法,我們常用獲得bean的方法getBean方法如下:
而大家程式碼第一步獲取xml物件的方法,對應介面其實是Resource介面,裡面也有很多常見的實現類。
太具體的原始碼 大家自己看看api就都懂了 粗淺的原理還是很容易懂得