核心技術(shù)-IoC容器

1浪规、IoC容器簡介

控制反轉(zhuǎn)IoC(Inversion of Control)又稱依賴注入DI(dependency injection)或听,由org.springframework.beans和org.springframework.context基礎(chǔ)包構(gòu)成了IoC容器,其中BeanFactory接口提供了一種先進(jìn)的配置機(jī)制能夠管理任何類型的對象罗丰,ApplicationContext是BeanFactory的一個(gè)子類神帅,它更加簡便的集成了Spring的AOP特性,通常情況下使用ApplicationContext萌抵,因?yàn)樗峁┝薆eanFactory的完整超集找御,如果想用BeanFactory替代ApplicationContext可以參考 Section 6.16, “The BeanFactory”
Spring IoC容器工作圖描述

Paste_Image.png

2元镀、源數(shù)據(jù)(Metadata)配置

可以基于以下三種方式配置:

  • xml注入
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd"> 
    <bean id="..." class="..."> <!-- collaborators and configuration for this bean go here --> 
    </bean> 
    <bean id="..." class="..."> <!-- collaborators and configuration for this bean go here --> 
    </bean> <!-- more bean definitions go here -->
</beans>

允許組合多個(gè)bean配置xml

<beans> 
    <import resource="services.xml"/> 
    <import resource="resources/messageSource.xml"/> 
    <import resource="/resources/themeSource.xml"/> 

    <bean id="bean1" class="..."/> 
    <bean id="bean2" class="..."/>
</beans>

使用容器加載bean

// create and configure beans
ApplicationContext context = new ClassPathXmlApplicationContext(new String[] {"services.xml", "daos.xml"});
// retrieve configured instance
PetStoreService service = context.getBean("petStore", PetStoreService.class);
// use configured instance
List<String> userList = service.getUsernameList();
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 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"> 
  <context:annotation-config/>
</beans>
@Configuration
public class AppConfig { 
    @Bean
    public MyService myService() { 
      return new MyServiceImpl(); 
    }
}

加載bean

ApplicationContext ctx = new AnnotationConfigApplicationContext(AppConfig.class); 
MyService myService = ctx.getBean(MyService.class); 
myService.doStuff();
3、實(shí)例化bean
  • 通過構(gòu)造函數(shù)實(shí)例化
<bean id="exampleBean" class="examples.ExampleBean"/>
  • 通過靜態(tài)方法實(shí)例化
    java code
public class ClientService { 
    private static ClientService clientService = new ClientService(); 
    private ClientService() {} 
    public static ClientService createInstance() { 
      return clientService; 
    }
}

xml配置

<bean id="clientService" class="examples.ClientService" factory-method="createInstance"/>

靜態(tài)方法帶參數(shù)(通過constructor-arg傳入?yún)?shù))
java code

public class ExampleBean { 
    // a private constructor 
    private ExampleBean(...) { ... } 
    // a static factory method; the arguments to this method can be 
    // considered the dependencies of the bean that is returned, 
    // regardless of how those arguments are actually used. 
    public static ExampleBean createInstance ( 
      AnotherBean anotherBean, YetAnotherBean yetAnotherBean, int i) { 
        ExampleBean eb = new ExampleBean (...); 
        // some other operations... return eb; 
    }
}

xml 配置

<bean id="exampleBean" class="examples.ExampleBean" factory-method="createInstance">
    <constructor-arg ref="anotherExampleBean"/> 
    <constructor-arg ref="yetAnotherBean"/> 
    <constructor-arg value="1"/>
</bean>
<bean id="anotherExampleBean" class="examples.AnotherBean"/>
<bean id="yetAnotherBean" class="examples.YetAnotherBean"/>
  • 通過普通方法實(shí)例化
    java code
public class DefaultServiceLocator { 
    private static ClientService clientService = new ClientServiceImpl(); 
    private DefaultServiceLocator() {} 
    public ClientService createClientServiceInstance() { 
        return clientService; 
    }
}

xml配置

<!-- the factory bean, which contains a method called createInstance() -->
<bean id="serviceLocator" class="examples.DefaultServiceLocator"> 
    <!-- inject any dependencies required by this locator bean -->
</bean>
<!-- the bean to be created via the factory bean -->
<bean id="clientService" factory-bean="serviceLocator" factory-method="createClientServiceInstance"/>
4霎桅、依賴注入
  • 基于構(gòu)造器的注入
    普通類型的參數(shù)
    java code
package x.y;
public class Foo { 
    public Foo(Bar bar, Baz baz) { 
    // ... 
    }
}

xml配置

<beans> 
    <bean id="foo" class="x.y.Foo"> 
       <constructor-arg ref="bar"/> 
       <constructor-arg ref="baz"/> 
    </bean> 
    <bean id="bar" class="x.y.Bar"/> 
    <bean id="baz" class="x.y.Baz"/>
</beans>

基本數(shù)據(jù)類型的參數(shù)
java code

package examples;
public class ExampleBean { 
    // Number of years to calculate the Ultimate Answer 
    private int years; 
    // The Answer to Life, the Universe, and Everything 
    private String ultimateAnswer; 
    public ExampleBean(int years, String ultimateAnswer) { 
      this.years = years; this.ultimateAnswer = ultimateAnswer; 
    }
}

xml配置-type

<bean id="exampleBean" class="examples.ExampleBean"> 
    <constructor-arg type="int" value="7500000"/> 
    <constructor-arg type="java.lang.String" value="42"/>
</bean>

xml配置-index

<bean id="exampleBean" class="examples.ExampleBean"> 
    <constructor-arg index="0" value="7500000"/> 
    <constructor-arg index="1" value="42"/>
</bean>

xml配置-name

<bean id="exampleBean" class="examples.ExampleBean"> 
    <constructor-arg name="years" value="7500000"/> 
    <constructor-arg name="ultimateAnswer " value="42"/>
</bean>

注意栖疑,基于那么的注入,如果你的編譯不是以debug方式編譯滔驶,那么參數(shù)名是會(huì)變掉遇革,這時(shí)候需要通過jdk注解指定編譯后的參數(shù)名

package examples;
public class ExampleBean { 
    // Fields omitted 
    @ConstructorProperties({"years", "ultimateAnswer"})
    public ExampleBean(int years, String ultimateAnswer) { 
      this.years = years; 
      this.ultimateAnswer = ultimateAnswer; 
    }
}
  • 基于setter的注入
    java code
public class SimpleMovieLister { 
    // the SimpleMovieLister has a dependency on the MovieFinder 
    private MovieFinder movieFinder; 
    // a setter method so that the Spring container can inject a MovieFinder 
    public void setMovieFinder(MovieFinder movieFinder) { 
      this.movieFinder = movieFinder; 
    } 
    // business logic that actually uses the injected MovieFinder is omitted...
}

xml配置

<bean id="simpleMovieLister" class="examples.SimpleMovieLister"> 
    <!-- setter injection using the nested ref element --> 
    <property name="movieFinder"> 
      <ref bean="movieFinderBean"/> 
    </property>
</bean>
<bean id="movieFinderBean" class="examples.MovieFinder"/>

該方式依賴注入由容器調(diào)用setter方法將匹配參數(shù)類型的bean注入進(jìn)去,所以該方式注入會(huì)在其它構(gòu)造器注入之后之后注入

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
  • 序言:七十年代末揭糕,一起剝皮案震驚了整個(gè)濱河市萝快,隨后出現(xiàn)的幾起案子,更是在濱河造成了極大的恐慌著角,老刑警劉巖揪漩,帶你破解...
    沈念sama閱讀 217,406評論 6 503
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件,死亡現(xiàn)場離奇詭異吏口,居然都是意外死亡奄容,警方通過查閱死者的電腦和手機(jī),發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 92,732評論 3 393
  • 文/潘曉璐 我一進(jìn)店門产徊,熙熙樓的掌柜王于貴愁眉苦臉地迎上來昂勒,“玉大人,你說我怎么就攤上這事舟铜「暧” “怎么了?”我有些...
    開封第一講書人閱讀 163,711評論 0 353
  • 文/不壞的土叔 我叫張陵深滚,是天一觀的道長奕谭。 經(jīng)常有香客問我,道長痴荐,這世上最難降的妖魔是什么? 我笑而不...
    開封第一講書人閱讀 58,380評論 1 293
  • 正文 為了忘掉前任官册,我火速辦了婚禮生兆,結(jié)果婚禮上,老公的妹妹穿的比我還像新娘膝宁。我一直安慰自己鸦难,他們只是感情好,可當(dāng)我...
    茶點(diǎn)故事閱讀 67,432評論 6 392
  • 文/花漫 我一把揭開白布员淫。 她就那樣靜靜地躺著合蔽,像睡著了一般。 火紅的嫁衣襯著肌膚如雪介返。 梳的紋絲不亂的頭發(fā)上拴事,一...
    開封第一講書人閱讀 51,301評論 1 301
  • 那天沃斤,我揣著相機(jī)與錄音,去河邊找鬼刃宵。 笑死衡瓶,一個(gè)胖子當(dāng)著我的面吹牛,可吹牛的內(nèi)容都是我干的牲证。 我是一名探鬼主播哮针,決...
    沈念sama閱讀 40,145評論 3 418
  • 文/蒼蘭香墨 我猛地睜開眼,長吁一口氣:“原來是場噩夢啊……” “哼坦袍!你這毒婦竟也來了十厢?” 一聲冷哼從身側(cè)響起,我...
    開封第一講書人閱讀 39,008評論 0 276
  • 序言:老撾萬榮一對情侶失蹤捂齐,失蹤者是張志新(化名)和其女友劉穎蛮放,沒想到半個(gè)月后,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體辛燥,經(jīng)...
    沈念sama閱讀 45,443評論 1 314
  • 正文 獨(dú)居荒郊野嶺守林人離奇死亡筛武,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點(diǎn)故事閱讀 37,649評論 3 334
  • 正文 我和宋清朗相戀三年,在試婚紗的時(shí)候發(fā)現(xiàn)自己被綠了挎塌。 大學(xué)時(shí)的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片徘六。...
    茶點(diǎn)故事閱讀 39,795評論 1 347
  • 序言:一個(gè)原本活蹦亂跳的男人離奇死亡,死狀恐怖榴都,靈堂內(nèi)的尸體忽然破棺而出待锈,到底是詐尸還是另有隱情,我是刑警寧澤嘴高,帶...
    沈念sama閱讀 35,501評論 5 345
  • 正文 年R本政府宣布竿音,位于F島的核電站,受9級特大地震影響拴驮,放射性物質(zhì)發(fā)生泄漏春瞬。R本人自食惡果不足惜,卻給世界環(huán)境...
    茶點(diǎn)故事閱讀 41,119評論 3 328
  • 文/蒙蒙 一套啤、第九天 我趴在偏房一處隱蔽的房頂上張望宽气。 院中可真熱鬧,春花似錦潜沦、人聲如沸萄涯。這莊子的主人今日做“春日...
    開封第一講書人閱讀 31,731評論 0 22
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽涝影。三九已至,卻和暖如春争占,著一層夾襖步出監(jiān)牢的瞬間燃逻,已是汗流浹背序目。 一陣腳步聲響...
    開封第一講書人閱讀 32,865評論 1 269
  • 我被黑心中介騙來泰國打工, 沒想到剛下飛機(jī)就差點(diǎn)兒被人妖公主榨干…… 1. 我叫王不留唆樊,地道東北人宛琅。 一個(gè)月前我還...
    沈念sama閱讀 47,899評論 2 370
  • 正文 我出身青樓,卻偏偏與公主長得像逗旁,于是被迫代替她去往敵國和親嘿辟。 傳聞我的和親對象是個(gè)殘疾皇子,可洞房花燭夜當(dāng)晚...
    茶點(diǎn)故事閱讀 44,724評論 2 354

推薦閱讀更多精彩內(nèi)容