Spring核心功能 - IOC

目錄說明

1 What is the IOC 踏志?


IOC(Inversion Of Control):即控制反轉丽猬,也被稱為依賴注入宿饱。控制反轉就是應用本身不負責依賴對象的創(chuàng)建和維護脚祟,將對象的創(chuàng)建和維護交給外部容器處理谬以。這樣應用的控制權就交給了外部容器,控制權的轉移就是控制反轉由桌,目的是為了獲得更好的維護性以及降低耦合度为黎。

2 Why use IOC ?


IOC 容器可以用來管理應用對象的配置和生命周期行您,配置每個對象的創(chuàng)建和銷毀铭乾,也可以配置每個 bean 是只有一個實例,還是每次需要時都生成一個新的實例(即singleton or prototype)娃循,以及它們是如何相互關聯(lián)的炕檩。

3 How to use IOC


3.1 環(huán)境搭建

【1】 導入 Spring 核心 jar 文件(最好使用版本 3.0+)

commons-logging-1.1.3.jar           日志
spring-beans-3.2.5.RELEASE.jar        bean節(jié)點
spring-context-3.2.5.RELEASE.jar       spring上下文節(jié)點
spring-core-3.2.5.RELEASE.jar         spring核心功能
spring-expression-3.2.5.RELEASE.jar    spring表達式相關表

【2】核心配置文件:applicationContext.xml / bean.xml

bean.xml

<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"
    xmlns:context="http://www.springframework.org/schema/context"
    xsi:schemaLocation="
        http://www.springframework.org/schema/beans
        http://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/context
        http://www.springframework.org/schema/context/spring-context.xsd">
    
</beans>   

【3】一個簡單的 IOC 容器的獲取

1 創(chuàng)建 User.class

class User{
  private Integer id;
  private String name;

setter .... getter
}

2 bean.xml 配置

<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"
    xmlns:context="http://www.springframework.org/schema/context"
    xsi:schemaLocation="
        http://www.springframework.org/schema/beans
        http://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/context
        http://www.springframework.org/schema/context/spring-context.xsd">
    
      <bean id="user" class="cn.acey1.User"></bean>
</beans>   

3 獲取 IOC 容器中的 User 對象

public class test{
    @Test
    public void testAc() throws Exception {
        // 得到IOC容器對象
        ApplicationContext ac = new ClassPathXmlApplicationContext("cn/acey1/bean.xml");
        // 從容器中獲取bean
        User user = (User) ac.getBean("user");
        
        System.out.println(user);
    }
}
3.2 bean 節(jié)點的說明

在 IOC 容器中存在多個 bean ,每個 bean 都對應著一個對象捌斧,當需要獲取該對象時笛质,直接從 IOC 容器中取。bean 節(jié)點中的幾個屬性說明

<bean id=" " 
      class=" " 
      scope=“ ” 
      lazy-init=“ ”
      init-method=“ ”
      destroy-method=“ ” 
/>
  • id : 在 IOC 容器中每個 bean 都對應著一個標示即id
  • class:id 對應的類
  • scope:創(chuàng)建方式捞蚂,默認是 singleton
  • singleton:單例经瓷,在容器啟動之前就創(chuàng)建 bean,在整個應用只有一個
  • prototype:多例洞难,在用到對象的時候就創(chuàng)建,整個應用中存在多個
  • lazy-init:是否延遲創(chuàng)建(只對 singleton 有效)揭朝,默認是 false
  • false:不延遲創(chuàng)建队贱,在啟動的時候就創(chuàng)建
  • true:延遲創(chuàng)建,在使用到的時候在創(chuàng)建
  • init-method:在對象創(chuàng)建時執(zhí)行該方法潭袱,該方法必須在該類中存在
  • destory-method :當容器銷毀時執(zhí)行的方法柱嫌,該方法必須在該類中存在
3.3 對象創(chuàng)建的幾種方式

【1】使用無參構造器

<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"
    xmlns:context="http://www.springframework.org/schema/context"
    xsi:schemaLocation="
        http://www.springframework.org/schema/beans
        http://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/context
        http://www.springframework.org/schema/context/spring-context.xsd">
    
      <bean id="user" class="cn.acey1.User"></bean>
</beans>   

【2】使用有參構造器

User.class

public class User{
 public User(int id , String name){
   ...
}
}

bean.xml

<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"
    xmlns:context="http://www.springframework.org/schema/context"
    xsi:schemaLocation="
        http://www.springframework.org/schema/beans
        http://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/context
        http://www.springframework.org/schema/context/spring-context.xsd">
    
      <bean id="user" class="cn.acey1.User">
         <constructor-arg index="0" type="int" value="100"></constructor-arg>
        <constructor-arg index="1" type="java.lang.String" value="Acey">
        </constructor-arg>
     </bean>
</beans>   

【3】工廠類創(chuàng)建:靜態(tài)和非靜態(tài)

UserFactory.class

public class UserFactory{

      //實例方法創(chuàng)建 User
       public User getUser(){
          return new User();
       }


      //靜態(tài)方法創(chuàng)建 User
       public static User getStaticUser(){
          return new User();
       }
}

bean.xml

<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"
    xmlns:context="http://www.springframework.org/schema/context"
    xsi:schemaLocation="
        http://www.springframework.org/schema/beans
        http://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/context
        http://www.springframework.org/schema/context/spring-context.xsd">

      <!-- #實例創(chuàng)建 -->
      <!-- 先創(chuàng)建工廠 -->
     <bean id="factory" class="cn.acey1.UserFactory"></bean>
    <!-- 在創(chuàng)建user對象,用factory的實例方法 -->
    <bean id="user" factory-bean="factory" factory-method="getUser"></bean>
    
    
    <!--  #靜態(tài)方法創(chuàng)建 -->
    <!-- 
        class 指定的就是工廠類型
        factory-method  一定是工廠里面的“靜態(tài)方法”
     -->
    <bean id="user" class="cn.acey1.UserFactory" factory-method="getStaticUser"></bean>
</beans>   

3.4 對象關系依賴(依賴注入)

【1】通過構造函數(shù)注入

【2】通過 set 方法注入

<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"
    xmlns:context="http://www.springframework.org/schema/context"
    xsi:schemaLocation="
        http://www.springframework.org/schema/beans
        http://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/context
        http://www.springframework.org/schema/context/spring-context.xsd">

   
      <!-- 基本類型注入 -->
     <bean id="user" class="cn.acey1.User">
        <property name="id" value="1">
        <property name="name" value="Acey">
     </bean>

      <!-- 引用類型注入 -->
    <bean id="str" class="java.lang.String">
        <constructor-arg value="Acey"></constructor-arg>
    </bean>
     <bean id="user" class="cn.acey1.User">
        <property name="name" ref="str">
     </bean>    
</beans>   

【3】p 名稱空間注入(優(yōu)化) Spring3.0+支持

<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"
    xmlns:context="http://www.springframework.org/schema/context"
    xsi:schemaLocation="
        http://www.springframework.org/schema/beans
        http://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/context
        http://www.springframework.org/schema/context/spring-context.xsd">

    <bean id="str" class="java.lang.String">
        <constructor-arg value="Acey"></constructor-arg>
    </bean>
     <bean id="user" class="cn.acey1.User"  p:ref-name="str"></bean>    
</beans>   

【4】注解

使用步驟:

  1. 引入 context 名稱空間
    xmlns:context="http://www.springframework.org/schema/context"
  2. 開啟注解掃描
    <context:component-scan base-package="cn.Acey"></context:component-scan>
  3. 使用注解
  • @Component 把指定的對象加入 IOC 容器
  • @scope("[ prototype / singleton]") 創(chuàng)建方式(多例/單例(default))
  • @Repository 作用同 @Component屯换,一般在持久層使用
  • @Service 作用同 @Component编丘,一般在業(yè)務層使用
  • @Controller 作用同 @Component与学,一般在控制層使用
  • @Resource 屬性注入
<!--持久層--!>
@Repository(value="userDao")
//等價于<bean id="userDao" class="cn.acey1.UserDao"></bean>
或者
@Repository   //如果不指定 value 值,那么默認的 bean 名字為該類名嘉抓,其中類名的首字母小寫
public class UserDao{
...
}

<!--業(yè)務層--!>
@Service
public class UserService{

    @Resource(name="userDao") //如果不指定 name 值索守,那么默認值就為屬性名
     private UserDao userDao;
}

<!--控制  層--!>
@Controller
@scope("prototype")//多例模式
public class UserAction{

}

所有實例代碼地址 https://github.com/Aceysx/SpringDemo

最后編輯于
?著作權歸作者所有,轉載或內容合作請聯(lián)系作者
  • 序言:七十年代末,一起剝皮案震驚了整個濱河市抑片,隨后出現(xiàn)的幾起案子卵佛,更是在濱河造成了極大的恐慌,老刑警劉巖敞斋,帶你破解...
    沈念sama閱讀 216,470評論 6 501
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件截汪,死亡現(xiàn)場離奇詭異,居然都是意外死亡植捎,警方通過查閱死者的電腦和手機衙解,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 92,393評論 3 392
  • 文/潘曉璐 我一進店門,熙熙樓的掌柜王于貴愁眉苦臉地迎上來焰枢,“玉大人蚓峦,你說我怎么就攤上這事∫阶桑” “怎么了枫匾?”我有些...
    開封第一講書人閱讀 162,577評論 0 353
  • 文/不壞的土叔 我叫張陵,是天一觀的道長拟淮。 經(jīng)常有香客問我干茉,道長,這世上最難降的妖魔是什么很泊? 我笑而不...
    開封第一講書人閱讀 58,176評論 1 292
  • 正文 為了忘掉前任角虫,我火速辦了婚禮,結果婚禮上委造,老公的妹妹穿的比我還像新娘戳鹅。我一直安慰自己,他們只是感情好昏兆,可當我...
    茶點故事閱讀 67,189評論 6 388
  • 文/花漫 我一把揭開白布枫虏。 她就那樣靜靜地躺著,像睡著了一般爬虱。 火紅的嫁衣襯著肌膚如雪隶债。 梳的紋絲不亂的頭發(fā)上,一...
    開封第一講書人閱讀 51,155評論 1 299
  • 那天跑筝,我揣著相機與錄音死讹,去河邊找鬼。 笑死曲梗,一個胖子當著我的面吹牛赞警,可吹牛的內容都是我干的妓忍。 我是一名探鬼主播,決...
    沈念sama閱讀 40,041評論 3 418
  • 文/蒼蘭香墨 我猛地睜開眼愧旦,長吁一口氣:“原來是場噩夢啊……” “哼世剖!你這毒婦竟也來了?” 一聲冷哼從身側響起忘瓦,我...
    開封第一講書人閱讀 38,903評論 0 274
  • 序言:老撾萬榮一對情侶失蹤搁廓,失蹤者是張志新(化名)和其女友劉穎,沒想到半個月后耕皮,有當?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體境蜕,經(jīng)...
    沈念sama閱讀 45,319評論 1 310
  • 正文 獨居荒郊野嶺守林人離奇死亡,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內容為張勛視角 年9月15日...
    茶點故事閱讀 37,539評論 2 332
  • 正文 我和宋清朗相戀三年凌停,在試婚紗的時候發(fā)現(xiàn)自己被綠了粱年。 大學時的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片。...
    茶點故事閱讀 39,703評論 1 348
  • 序言:一個原本活蹦亂跳的男人離奇死亡罚拟,死狀恐怖台诗,靈堂內的尸體忽然破棺而出,到底是詐尸還是另有隱情赐俗,我是刑警寧澤拉队,帶...
    沈念sama閱讀 35,417評論 5 343
  • 正文 年R本政府宣布,位于F島的核電站阻逮,受9級特大地震影響粱快,放射性物質發(fā)生泄漏。R本人自食惡果不足惜叔扼,卻給世界環(huán)境...
    茶點故事閱讀 41,013評論 3 325
  • 文/蒙蒙 一事哭、第九天 我趴在偏房一處隱蔽的房頂上張望。 院中可真熱鬧瓜富,春花似錦鳍咱、人聲如沸。這莊子的主人今日做“春日...
    開封第一講書人閱讀 31,664評論 0 22
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽。三九已至价捧,卻和暖如春每辟,著一層夾襖步出監(jiān)牢的瞬間,已是汗流浹背干旧。 一陣腳步聲響...
    開封第一講書人閱讀 32,818評論 1 269
  • 我被黑心中介騙來泰國打工, 沒想到剛下飛機就差點兒被人妖公主榨干…… 1. 我叫王不留妹蔽,地道東北人椎眯。 一個月前我還...
    沈念sama閱讀 47,711評論 2 368
  • 正文 我出身青樓挠将,卻偏偏與公主長得像,于是被迫代替她去往敵國和親编整。 傳聞我的和親對象是個殘疾皇子舔稀,可洞房花燭夜當晚...
    茶點故事閱讀 44,601評論 2 353

推薦閱讀更多精彩內容