當前位置:
首頁 >
前端技术
> javascript
>内容正文
javascript
大数据WEB阶段Spring框架(一)IOC控制反转、DI注入依赖
生活随笔
收集整理的這篇文章主要介紹了
大数据WEB阶段Spring框架(一)IOC控制反转、DI注入依赖
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
Spring-IOC、DI
零、Spring簡介
- Spring官網:http://projects.spring.io/spring-framework
- Jar包的下載地址:http://repo.spring.io/release/org/springframework/spring
- Spring框架的特點:
- spring的是一個輕量級的框架(減少侵入性,對容器沒有依賴性,無需修改代碼)
- spring能整合其他主流框架
一、Spring-IOC控制反轉
什么是IOC?
- 把對象的創建、初始化、銷毀等工作交給Spring容器來做。
- Spring容器控制對象的生命周期。
- 以前: Person p1 = new Person(); 手動的創建對象
- 現在: Person p1 = Spring容器.get***(); Spring容器來創建
- 說明:通過Spring容器來管理對象更加簡單,不用關心對象的創建過程!!
解耦! 用IOC來創建對象
具體步驟
1.先導入Spring相關JAR包
2.創建對象類
3.編輯xml配置文件
二、依賴注入
示例:
public class Person {private Student student;private int number;private String str;private List list;private Set set;private Map map;private Properties properties;}<!-- set方式注入 --><bean id="person" class="domain.Person"><!-- property屬性 name="student" ref="student"引用的名稱 --><!-- 對象要有set方法 如果沒有set方法會報錯 --><!-- <property name="student" ref="student"></property> --><property name="student"><ref bean="student"/></property><!--注入基本類型 --><property name="number" value="2016"></property><!--注入String --><property name="str" value="我是一只小小小小鳥"></property><!--注入List --><property name="list" ><list><value>111</value><value>想要飛啊飛,飛的更好</value><ref bean="student"/></list></property><!--注入set --><property name="set"><set><value>111</value><value>111</value><value>你是我的優樂美</value><ref bean="student"/></set></property><!--注入MAP --><property name="map"><map><entry key="1" value="上路英雄"></entry><entry key="2" value="大野英雄"></entry><entry key="3" value="中單英雄"></entry><entry key="4" value="ADC"></entry><entry key="5" value="輔助"></entry><entry key="student" value-ref="student"></entry></map><!--map的實現有序是LinkedHashMap --></property><!--注入propertys --><property name="properties"><props><prop key="p1">你好</prop><prop key="p2">訂單</prop><prop key="p3">333</prop></props></property></bean><bean id="student" class="domain.Student"></bean><!-- 構造函數方式注入 --><bean id="person" class="domain.Person"><!--構造方法賦值 index="參數位置" 從0開始 name="" 參數的名稱type="" 參數類型 value="基本類型" ref="引用類型"--><!-- 測試一個參數的構造器賦值--><constructor-arg index="0" name="student" ref="student"></constructor-arg><constructor-arg index="1" name="number" value="100"></constructor-arg><constructor-arg index="2" name="str" value="劉昱江"></constructor-arg><constructor-arg name="list"><list><value>sss</value><value>劉昱江</value></list></constructor-arg>index和 name配置一個即可 , 但是通常使用index , 因為項目改動時形參名可能會變三、IOC和DI的意義
- 傳統的mvc思想中代碼的侵入性特別強,緊耦合,如果想換實現類,只能修改代碼完成。所以IOC和DI的出現解決了這個問題。實現代碼的松耦合。真正意義上的面向切面編程
總結
以上是生活随笔為你收集整理的大数据WEB阶段Spring框架(一)IOC控制反转、DI注入依赖的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 大数据WEB阶段总结
- 下一篇: 大数据WEB阶段Spring框架(二)简