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