spring IOC和DI
spring IOC and DI
1、IOC和DI的區(qū)別:
IOC:對(duì)象的管理權(quán)由spring容器掌握(管理權(quán)限包括:對(duì)象的創(chuàng)建時(shí)間點(diǎn)、創(chuàng)建方式以及對(duì)象屬性的管理);
DI:spring操作對(duì)象屬性的時(shí)使用的方式就是DI技術(shù)
2、DI方式:spring操作對(duì)象屬性的時(shí)間點(diǎn)一般都是在對(duì)象創(chuàng)建的時(shí)候,操作的方式是可配置的,主要有4種方式:no(default)、byName、byType、constructor。
no方式:這是spring的默認(rèn)方式,這種方式spring不會(huì)對(duì)對(duì)象的屬性做任何的操作,除非配置了<property>屬性,否則spring不會(huì)自動(dòng)的在當(dāng)前context去找需要的值。
byName方式:spring會(huì)在當(dāng)前的context找到和對(duì)象屬性名稱相同的值進(jìn)行注入,如果找到的值的類型和屬性的值類型不一致就會(huì)報(bào):"Cannot convert value of type"錯(cuò)誤。
byType方式:spring會(huì)在當(dāng)前的context找到和對(duì)象屬性類型相同的值進(jìn)行注入,如果找到值不止一個(gè)就會(huì)報(bào)"No unique bean of type"錯(cuò)誤。
constructor方式:這種方式比較特殊,這是一個(gè)顯示的依賴關(guān)系,對(duì)象必須有有參構(gòu)造方法,spring會(huì)根據(jù)參數(shù)的名稱去context找對(duì)應(yīng)的值進(jìn)行注入,改方式不能被子類繼承。
3、IOC用法:
3.1、創(chuàng)建子類對(duì)象,給其指定父類對(duì)象,如果不指定那么父類會(huì)重新實(shí)例化,不會(huì)再當(dāng)前容器中查找。
<bean name="student" class="com.xxw.pojo.Student" parent="persion">
<property name="name" value="this a student"/>
</bean>
<bean name="persion" class="com.xxw.pojo.Persion" autowire="byName" >
<property name="persionName" value="this is two persion"/>
</bean>
其他兩種:可以通過(guò)靜態(tài)工廠方法或者實(shí)例工廠的方法
4、spring元數(shù)據(jù)配置中的p標(biāo)簽和c標(biāo)簽
使用p標(biāo)簽需要加入xml:xmlns:p="http://www.springframework.org/schema/p"
<bean name="animal" class="com.xxw.pojo.Cat" p:name="this is cat" />
等價(jià)于:
<bean name="animal" class="com.xxw.pojo.Cat">
<property name="name" value="this is cat"/>
</bean>
使用c標(biāo)簽需要加入xml: xmlns:c="http://www.springframework.org/schema/c"
這個(gè)標(biāo)簽的使用類似于:<constructor-arg></constructor-arg>標(biāo)簽
轉(zhuǎn)載于:https://www.cnblogs.com/xxw-it/p/3647777.html
《新程序員》:云原生和全面數(shù)字化實(shí)踐50位技術(shù)專家共同創(chuàng)作,文字、視頻、音頻交互閱讀總結(jié)
以上是生活随笔為你收集整理的spring IOC和DI的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。
- 上一篇: php使用第三方登录
- 下一篇: C++中 #include与#inclu