spring之IOC

Spring之IOC(DI)

控制反轉(zhuǎn) Inversion of Control
依賴注入 Dependency Injection and

下面通過(guò)一個(gè)例子學(xué)習(xí)spring的IOC。

一個(gè)例子

源代碼目錄結(jié)構(gòu)如下:

main
    service
        UserService
    dao
        UserDao(接口)
        UserDaoImpl
    model
        User
    beans.xml

假如我們想實(shí)現(xiàn)一個(gè)如下功能:調(diào)用service層的UserService保存用戶數(shù)據(jù)。在UserService中調(diào)用UserDao存入數(shù)據(jù)庫(kù)。
在沒(méi)有spring之前萧福,我們?cè)趕ervice層使用dao層功能的時(shí)候需要一個(gè)實(shí)現(xiàn)了UserDao的實(shí)例對(duì)象琴许,即顯式new一個(gè)對(duì)象逢享。
spring是怎么幫我們做的呢?



如圖,我們只需要在配置文件中配置相關(guān)信息遭顶,spring容器會(huì)自動(dòng)替我們創(chuàng)建對(duì)象。
XML配置文件如下:

    <bean id="user" class="main.dao.UserDaoImpl">
    </bean>
    
    <bean id="userService" class="main.service.UserService">
        <property name="userDao" ref="user"></property>
    </bean>

test文件

@Test
    public void test() {
        // 通過(guò)指定XML文件得到一個(gè)ApplicationContext對(duì)象
        ApplicationContext context = new ClassPathXmlApplicationContext("main/beans.xml");
        // 通過(guò)配置文件中的bean得到一個(gè)UserService對(duì)象
        UserService service = (UserService) context.getBean("userService");
        service.add();
    }

spring是怎么幫我們做的呢泪蔫?首先解析配置文件棒旗,通過(guò)反射得到所有的bean對(duì)象,調(diào)用UserService的setUserDao方法撩荣,注入U(xiǎn)serDao到userService中铣揉。
** 上述例子通過(guò)XML配置userService和userDao之間的依賴關(guān)系,我們也可通過(guò)注解的方式配置兩者之間的關(guān)系餐曹。 **
首先我們需要在配置文件中加入一行配置:

<?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/>
<context:annotation-config/>

要記得引入context的約束文件逛拱。
接著用注解@Autowired,@Autowired放在如下地方:

  • setter
  • 構(gòu)造方法
  • 接口
    在我們的例子中:
public class UserService {   
    private UserDao userDao;
    @Autowired
    public void setUserDao(UserDao userDao) {
        this.userDao = userDao;
    }
    public void add () {
        userDao.save(new User());
    }
}

@Autowired 注解默認(rèn)按類型在bean容器中尋找需要的UserDao台猴,如果UserDao有多個(gè)實(shí)現(xiàn)怎么辦朽合?
這個(gè)時(shí)候需要另一個(gè)注解@Qualifier縮小范圍俱两。
它的使用如下:

    @Autowired
    @Qualifier("main")
    public void setUserDao(UserDao userDao) {
        this.userDao = userDao;
    }

在XML中配置bean的qualifier屬性

    <bean id="user" class="main.dao.UserDaoImpl">
        <qualifier value="main"></qualifier>
    </bean>

其實(shí)bean的name是默認(rèn)的qualifier value,我們也可以用id代替qualifier 元素曹步。

前面的先放一下宪彩,來(lái)看一段官方文檔:

Most examples in this chapter use XML to specify the configuration metadata that produces each BeanDefinition within the Spring container. The previous section demonstrates how to provide a lot of the configuration metadata through source-level annotations. Even in those examples, however, the "base" bean definitions are explicitly defined in the XML file, while the annotations only drive the dependency injection. This section describes an option for implicitly detecting the candidate components by scanning the classpath.Candidate components are classes that match against a filter criteria and have a corresponding bean definition registered with the container. This removes the need to use XML to perform bean registration, instead you can use annotations (for example @Component), AspectJ type expressions, or your own custom filter criteria to select which classes will have bean definitions registered with the container.

在配置文件中加入這句:
<context:component-scan base-package="org.example"/>
一個(gè)@Component注解即可讓spring自動(dòng)尋找需要的bean。

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
  • 序言:七十年代末讲婚,一起剝皮案震驚了整個(gè)濱河市尿孔,隨后出現(xiàn)的幾起案子,更是在濱河造成了極大的恐慌筹麸,老刑警劉巖活合,帶你破解...
    沈念sama閱讀 223,126評(píng)論 6 520
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件,死亡現(xiàn)場(chǎng)離奇詭異竹捉,居然都是意外死亡芜辕,警方通過(guò)查閱死者的電腦和手機(jī),發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 95,421評(píng)論 3 400
  • 文/潘曉璐 我一進(jìn)店門块差,熙熙樓的掌柜王于貴愁眉苦臉地迎上來(lái)侵续,“玉大人,你說(shuō)我怎么就攤上這事憨闰∽次希” “怎么了?”我有些...
    開(kāi)封第一講書人閱讀 169,941評(píng)論 0 366
  • 文/不壞的土叔 我叫張陵鹉动,是天一觀的道長(zhǎng)轧坎。 經(jīng)常有香客問(wèn)我,道長(zhǎng)泽示,這世上最難降的妖魔是什么缸血? 我笑而不...
    開(kāi)封第一講書人閱讀 60,294評(píng)論 1 300
  • 正文 為了忘掉前任,我火速辦了婚禮械筛,結(jié)果婚禮上捎泻,老公的妹妹穿的比我還像新娘。我一直安慰自己埋哟,他們只是感情好笆豁,可當(dāng)我...
    茶點(diǎn)故事閱讀 69,295評(píng)論 6 398
  • 文/花漫 我一把揭開(kāi)白布。 她就那樣靜靜地躺著赤赊,像睡著了一般闯狱。 火紅的嫁衣襯著肌膚如雪。 梳的紋絲不亂的頭發(fā)上抛计,一...
    開(kāi)封第一講書人閱讀 52,874評(píng)論 1 314
  • 那天哄孤,我揣著相機(jī)與錄音,去河邊找鬼吹截。 笑死瘦陈,一個(gè)胖子當(dāng)著我的面吹牛朦肘,可吹牛的內(nèi)容都是我干的。 我是一名探鬼主播双饥,決...
    沈念sama閱讀 41,285評(píng)論 3 424
  • 文/蒼蘭香墨 我猛地睜開(kāi)眼媒抠,長(zhǎng)吁一口氣:“原來(lái)是場(chǎng)噩夢(mèng)啊……” “哼!你這毒婦竟也來(lái)了咏花?” 一聲冷哼從身側(cè)響起趴生,我...
    開(kāi)封第一講書人閱讀 40,249評(píng)論 0 277
  • 序言:老撾萬(wàn)榮一對(duì)情侶失蹤,失蹤者是張志新(化名)和其女友劉穎昏翰,沒(méi)想到半個(gè)月后苍匆,有當(dāng)?shù)厝嗽跇?shù)林里發(fā)現(xiàn)了一具尸體,經(jīng)...
    沈念sama閱讀 46,760評(píng)論 1 321
  • 正文 獨(dú)居荒郊野嶺守林人離奇死亡棚菊,尸身上長(zhǎng)有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點(diǎn)故事閱讀 38,840評(píng)論 3 343
  • 正文 我和宋清朗相戀三年浸踩,在試婚紗的時(shí)候發(fā)現(xiàn)自己被綠了。 大學(xué)時(shí)的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片统求。...
    茶點(diǎn)故事閱讀 40,973評(píng)論 1 354
  • 序言:一個(gè)原本活蹦亂跳的男人離奇死亡检碗,死狀恐怖,靈堂內(nèi)的尸體忽然破棺而出码邻,到底是詐尸還是另有隱情折剃,我是刑警寧澤,帶...
    沈念sama閱讀 36,631評(píng)論 5 351
  • 正文 年R本政府宣布像屋,位于F島的核電站怕犁,受9級(jí)特大地震影響,放射性物質(zhì)發(fā)生泄漏己莺。R本人自食惡果不足惜奏甫,卻給世界環(huán)境...
    茶點(diǎn)故事閱讀 42,315評(píng)論 3 336
  • 文/蒙蒙 一、第九天 我趴在偏房一處隱蔽的房頂上張望凌受。 院中可真熱鬧阵子,春花似錦、人聲如沸胁艰。這莊子的主人今日做“春日...
    開(kāi)封第一講書人閱讀 32,797評(píng)論 0 25
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽(yáng)腾么。三九已至,卻和暖如春杈湾,著一層夾襖步出監(jiān)牢的瞬間解虱,已是汗流浹背。 一陣腳步聲響...
    開(kāi)封第一講書人閱讀 33,926評(píng)論 1 275
  • 我被黑心中介騙來(lái)泰國(guó)打工漆撞, 沒(méi)想到剛下飛機(jī)就差點(diǎn)兒被人妖公主榨干…… 1. 我叫王不留殴泰,地道東北人于宙。 一個(gè)月前我還...
    沈念sama閱讀 49,431評(píng)論 3 379
  • 正文 我出身青樓,卻偏偏與公主長(zhǎng)得像悍汛,于是被迫代替她去往敵國(guó)和親捞魁。 傳聞我的和親對(duì)象是個(gè)殘疾皇子,可洞房花燭夜當(dāng)晚...
    茶點(diǎn)故事閱讀 45,982評(píng)論 2 361

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