業務場景: 在使用java進行開發業務的過程中,很多時候一個業務是由各種組件組成,在每個使用到這些組件時都會毫不猶豫的new一個組件對象來使用,在小項目中這樣的做法無可厚非,也不存在什么問題。但是在業務邏輯復雜并且多人協作開發的項目中,這會導致業務和組件之間的關系錯綜復雜而且不便于管理,對象之間的耦合度變得很高,這就是所謂的牽一發而動全身吧。 而這個問題在spring中得到了解決,它的核心在于ioc思想:
ioc:全文是inversion of control。翻譯過來就是控制反轉,意思是對象之間的關系不再由傳統的程序來控制,而是由spring容器來統一控制這些對象創建、協調、銷毀,而對象只需要完成業務邏輯即可。
這里引用一個叫bromon的blog對ioc的講解:
首先想說說ioc(inversion of control,控制倒轉) 這是spring的核心,貫穿始終。所謂ioc,對于spring框架來說,就是由spring來負責控制對象的生命周期和對象間的關系。舉個例子,我們是如何找女朋友的?常見的情況是,我們到處去看哪里有長得漂亮身材又好的mm,然后打聽她們的興趣愛好、qq號、電話號…,想辦法認識她們,投其所好送其所好,然后嘿嘿…這個過程是復雜深奧的,我們必須自己設計和面對每個環節。 傳統的程序開發也是如此,在一個對象中,如果要使用另外的對象,就必須得到它(自己new一個,或者從jndi中查詢一個),使用完之后還要將對象銷毀(比如connection等),對象始終會和其他的接口或類藕合起來。
那么ioc是如何做的呢?有點像通過婚介找女朋友,在我和女朋友之間引入了一個第三者:婚姻介紹所。婚介管理了很多男男女女的資料,我可以向婚介提出一個列表,告訴它我想找個什么樣的女朋友,比如長得像李嘉欣,身材像林熙雷,技術像齊達內之類的,然后婚介就會按照我們的要求,提供一個mm,我們只需要去和她談戀愛、結婚就行了。簡單明了,如果婚介給我們的人選不符合要求,我們就會拋出異常。整個過程不再由我自己控制,而是有婚介這樣一個類似容器的機構來控制。
spring所倡導的開發方式就是如此:所有的類都會在spring容器中登記,告訴spring你是個什么東西,你需要什么東西,然后spring會在系統運行到適當的時候,把你要的東西主動給你,同時也把你交給其他需要你的東西。所有的類的創建、銷毀都由 spring來控制,也就是說控制對象生存周期的不再是引用它的對象,而是spring。對于某個具體的對象而言,以前是它控制其他對象,現在是所有對象都被spring控制,所以這叫控制反轉。
ioc的一個重點是在系統運行中,動態的向某個對象提供它所需要的其他對象。這一點是通過di(dependency injection,依賴注入)來實現的。比如對象a需要操作數據庫,以前我們總是要在a中自己編寫代碼來獲得一個connection對象,有了 spring我們就只需要告訴spring,a中需要一個connection,至于這個connection怎么構造,何時構造,a不需要知道。在系統運行時,spring會在適當的時候制造一個connection,然后像打針一樣,注射到a當中,這樣就完成了對各個對象之間關系的控制。a需要依賴 connection才能正常運行,而這個connection是由spring注入到a中的,依賴注入的名字就這么來的。 那么di是如何實現的呢? java 1.3之后一個重要特征是反射(reflection),它允許程序在運行的時候動態的生成對象、執行對象的方法、改變對象的屬性,spring就是通過反射來實現注入的。
下面來讓大家了解一下spring到底是怎么運行的
1
2
3
4
5
6
|
public static void main(string[] args) { applicationcontext context = new filesystemxmlapplicationcontext( "applicationcontext.xml" ); animal animal = (animal) context.getbean( "animal" ); animal.say(); } |
這段代碼你一定很熟悉吧,不過還是讓我們分析一下它吧,首先是applicationcontext.xml
1
2
3
|
<bean id= "animal" class = "phz.springframework.test.cat" > <property name= "name" value= "kitty" /> </bean> |
他有一個類phz.springframework.test.cat
1
2
3
4
5
6
7
8
9
|
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接口
1
2
3
|
public interface animal { public void say(); } |
很明顯上面的代碼輸出i am kitty! 那么到底spring是如何做到的呢? 接下來就讓我們自己寫個spring 來看看spring 到底是怎么運行的吧! 首先,我們定義一個bean類,這個類用來存放一個bean擁有的屬性
1
2
3
4
5
6
|
/* 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配置可以像下面的
1
2
3
4
5
6
7
8
9
10
11
12
|
<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是怎樣保存上面的配置呢?,代碼如下:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
|
(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中的類屬性注入到類中。讓我們看看具體它是怎么做的吧。 首先實例化一個類,像這樣
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
|
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; } |
接著它將這個類的依賴注入進去,像這樣
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
|
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注入到需要注入的類中,像這樣:
1
2
3
4
5
6
7
8
9
10
11
12
13
|
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實現ioc的原理。
原文鏈接:http://blog.51cto.com/13941961/2178777