spring 入門例子--spring注入方式(設(shè)值注入&構(gòu)造器注入)

工具準(zhǔn)備

- myeclipse(10.7.1)

創(chuàng)建一個(gè)java web項(xiàng)目并添加spiing支持(或打開一個(gè)項(xiàng)目)

實(shí)現(xiàn)的業(yè)務(wù)邏輯


image.png
  • 上圖中InjectionServiceImpl有InjectionDAO的變量到踏,當(dāng)沒有主動(dòng)去創(chuàng)建蝠猬,而是通過配置文件配置抛丽,讓spring幫我們?nèi)ネ瓿?/li>
  • 目標(biāo)1通過xml文件配置實(shí)現(xiàn)設(shè)置注入

工程目錄結(jié)構(gòu)展示

image.png

為項(xiàng)目添加spring環(huán)境支持


image.png

此時(shí)myeclipse自動(dòng)為我們引入spring的jar包
并自動(dòng)創(chuàng)建applicationContext.xml(spring的配置文件)

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

參考:Eclipse/MyEclipse上配置Spring環(huán)境

創(chuàng)建InjectionDAO接口及其實(shí)現(xiàn)類InjectionDAOImpl

InjectionDAO.java

package com.younghare.interfaces;
public interface InjectionDAO {
    public void save(String arg);

}

實(shí)現(xiàn)類InjectionDAOImpl .java

package com.younghare.Impl;

import com.younghare.interfaces.InjectionDAO;

public class InjectionDAOImpl implements InjectionDAO {

    @Override
    public void save(String arg) {
        //模擬保存數(shù)據(jù)到數(shù)據(jù)庫
        System.out.println("模擬保存數(shù)據(jù)到數(shù)據(jù)庫:"+arg);
        
    }
}

創(chuàng)建InjectionService接口及其實(shí)現(xiàn)類InjectionServiceImpl

InjectionService.java

package com.younghare.interfaces;

public interface InjectionService {
    public void save(String arg);

}

InjectionServiceImpl.java(實(shí)現(xiàn)類)

package com.younghare.Impl;

import com.younghare.interfaces.InjectionDAO;
import com.younghare.interfaces.InjectionService;

public class InjectionServiceImpl implements InjectionService {
    private InjectionDAO injectionDAO; //模擬設(shè)值注入時(shí)需要為其生成set方法
    //sprint Ioc容器 的設(shè)值注入需要這個(gè)set方法
    public void setInjectionDAO(InjectionDAO injectionDAO) {
        this.injectionDAO = injectionDAO;
    }


    @Override
    public void save(String arg) {
        //模擬業(yè)務(wù)操作
        System.out.println("模擬業(yè)務(wù)操作");
        //對數(shù)據(jù)進(jìn)行處理---模擬經(jīng)過業(yè)務(wù)邏輯處理
        arg =arg +":"+ this.hashCode();
        //調(diào)用DAO把數(shù)據(jù)保存到數(shù)據(jù)庫
        injectionDAO.save(arg);
        
    }
}

配置applicationContext.xml(對bean進(jìn)行設(shè)置注入配置)

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

    <bean id="injectionService" class ="com.younghare.Impl.InjectionServiceImpl">
    <!--屬性name中的injectionDAO對應(yīng)的是InjectionServiceImpl成員變量的  -->
        <property name="injectionDAO" ref ="injectionDAO"></property>
    </bean>

    <bean id="injectionDAO" class ="com.younghare.Impl.InjectionDAOImpl"></bean>

</beans>
image.png

注意:你也可以在其他文件中進(jìn)行配置,比如spring-injection.xml,主要是與ClassPathXmlApplicationContext參數(shù)對應(yīng)
ApplicationContext appCtx = new ClassPathXmlApplicationContext("applicationContext.xml");

測試--創(chuàng)建SpringMain.java并實(shí)現(xiàn)main方法

測試代碼

package com.younghare.main;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

import com.younghare.Impl.InjectionServiceImpl;
import com.younghare.interfaces.InjectionService;

public class SpringMain {


    public static void main(String[] args) {
        // 測試java bean婆咸,配置信息在applicationContext.xml文件中
        ApplicationContext appCtx = new ClassPathXmlApplicationContext("applicationContext.xml");
        
        InjectionService injectionService = (InjectionService) appCtx.getBean("injectionService");
        injectionService.save("這是要保持的數(shù)據(jù)");

    }

}

運(yùn)行結(jié)果

image.png

現(xiàn)在實(shí)現(xiàn)構(gòu)造器注入

刪除xml配置文件中的設(shè)值注入的配置屯伞,并添加構(gòu)造器部分的注入

image.png
<?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:p="http://www.springframework.org/schema/p"
    xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.1.xsd">
    <!--構(gòu)造器注入  -->
    <bean id="injectionService" class ="com.younghare.Impl.InjectionServiceImpl">
        <constructor-arg name ="injectionDAO" ref ="injectionDAO"></constructor-arg>
    </bean>

    <bean id="injectionDAO" class ="com.younghare.Impl.InjectionDAOImpl"></bean>

</beans>

InjectionServiceImpl.java中添加InjectionServiceImpl構(gòu)造器injectionDAO的參數(shù)

image.png

再測試運(yùn)行結(jié)果也是

image.png

注意點(diǎn)如果構(gòu)造器參數(shù)的名稱定義不同與xml中饲化,則會(huì)報(bào)錯(cuò)--引用配置錯(cuò)誤
如把xml配置中改為injectionDAO3


xml配置引用與構(gòu)造器參數(shù)不一致

單元測試部分

在工程目錄中創(chuàng)建測試代碼管理目錄
myeclipse/new/Source Folder


image.png

創(chuàng)建單元測試類

在工程目錄中創(chuàng)建一個(gè)test類
myeclipse/new/other

image.png
image.png

SpringTest.java


import static org.junit.Assert.*;

import org.junit.BeforeClass;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

import com.younghare.interfaces.InjectionService;

public class SpringTest {
    
    private static ApplicationContext context =null;

    @BeforeClass
    public static void setUpBeforeClass() throws Exception {
        //加載Spring 的配置文件
        context = new ClassPathXmlApplicationContext("applicationContext.xml");
    }

    @Test
    public void test() {
        InjectionService injectionService  =(InjectionService) context.getBean("injectionService");
        injectionService.save("這是要保持的數(shù)據(jù)");
        
    }

}

運(yùn)行測試用例

右鍵/Run as/Junit Test


image.png

單元測試2方法

單元測試基礎(chǔ)類UnitTestBase.java

package com.younghare;

import org.junit.After;
import org.junit.Before;
import org.springframework.beans.BeansException;
import org.springframework.context.support.ClassPathXmlApplicationContext;
//import org.springframework.util.StringUtils;
import org.apache.commons.lang.StringUtils;

public class UnitTestBase {
    
    private ClassPathXmlApplicationContext context;
    
    private String springXmlpath;
    
    public UnitTestBase() {}
    
    public UnitTestBase(String springXmlpath) {
        this.springXmlpath = springXmlpath;
    }
    
    @Before
    public void before() {
        if (StringUtils.isEmpty(springXmlpath)) {
//          springXmlpath = "classpath*:spring-*.xml";
            springXmlpath = "classpath*:applicationContext*.xml";
            
        }
        try {
            context = new ClassPathXmlApplicationContext(springXmlpath.split("[,\\s]+"));
            context.start();
        } catch (BeansException e) {
            e.printStackTrace();
        }
    }
    
    @After
    public void after() {
        context.destroy();
    }
    
    @SuppressWarnings("unchecked")
    protected <T extends Object> T getBean(String beanId) {
        try {
            return (T)context.getBean(beanId);
        } catch (BeansException e) {
            e.printStackTrace();
            return null;
        }
    }
    
    protected <T extends Object> T getBean(Class<T> clazz) {
        try {
            return context.getBean(clazz);
        } catch (BeansException e) {
            e.printStackTrace();
            return null;
        }
    }

}

InjectionServiceTest.java (測試測試構(gòu)造器注入)

package com.younghare;

import static org.junit.Assert.*;

import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.BlockJUnit4ClassRunner;

import com.younghare.interfaces.InjectionService;

@RunWith(BlockJUnit4ClassRunner.class)
public class InjectionServiceTest extends UnitTestBase {

    public InjectionServiceTest() {
        //super();
        super("classpath:applicationContext.xml");
        
    }
    
    //構(gòu)造器注入
    @Test
    public void testconstructor() {
        InjectionService service = super.getBean("injectionService");
        service.save("這是要保存的數(shù)據(jù)");
    }

}

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
  • 序言:七十年代末,一起剝皮案震驚了整個(gè)濱河市金蜀,隨后出現(xiàn)的幾起案子刷后,更是在濱河造成了極大的恐慌,老刑警劉巖渊抄,帶你破解...
    沈念sama閱讀 222,946評論 6 518
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件尝胆,死亡現(xiàn)場離奇詭異,居然都是意外死亡护桦,警方通過查閱死者的電腦和手機(jī)含衔,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 95,336評論 3 399
  • 文/潘曉璐 我一進(jìn)店門,熙熙樓的掌柜王于貴愁眉苦臉地迎上來二庵,“玉大人贪染,你說我怎么就攤上這事〈呦恚” “怎么了杭隙?”我有些...
    開封第一講書人閱讀 169,716評論 0 364
  • 文/不壞的土叔 我叫張陵,是天一觀的道長因妙。 經(jīng)常有香客問我痰憎,道長,這世上最難降的妖魔是什么兰迫? 我笑而不...
    開封第一講書人閱讀 60,222評論 1 300
  • 正文 為了忘掉前任,我火速辦了婚禮炬称,結(jié)果婚禮上汁果,老公的妹妹穿的比我還像新娘。我一直安慰自己玲躯,他們只是感情好据德,可當(dāng)我...
    茶點(diǎn)故事閱讀 69,223評論 6 398
  • 文/花漫 我一把揭開白布鳄乏。 她就那樣靜靜地躺著,像睡著了一般棘利。 火紅的嫁衣襯著肌膚如雪橱野。 梳的紋絲不亂的頭發(fā)上,一...
    開封第一講書人閱讀 52,807評論 1 314
  • 那天善玫,我揣著相機(jī)與錄音水援,去河邊找鬼。 笑死茅郎,一個(gè)胖子當(dāng)著我的面吹牛蜗元,可吹牛的內(nèi)容都是我干的。 我是一名探鬼主播系冗,決...
    沈念sama閱讀 41,235評論 3 424
  • 文/蒼蘭香墨 我猛地睜開眼奕扣,長吁一口氣:“原來是場噩夢啊……” “哼!你這毒婦竟也來了掌敬?” 一聲冷哼從身側(cè)響起惯豆,我...
    開封第一講書人閱讀 40,189評論 0 277
  • 序言:老撾萬榮一對情侶失蹤,失蹤者是張志新(化名)和其女友劉穎奔害,沒想到半個(gè)月后楷兽,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體,經(jīng)...
    沈念sama閱讀 46,712評論 1 320
  • 正文 獨(dú)居荒郊野嶺守林人離奇死亡舀武,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點(diǎn)故事閱讀 38,775評論 3 343
  • 正文 我和宋清朗相戀三年拄养,在試婚紗的時(shí)候發(fā)現(xiàn)自己被綠了。 大學(xué)時(shí)的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片银舱。...
    茶點(diǎn)故事閱讀 40,926評論 1 353
  • 序言:一個(gè)原本活蹦亂跳的男人離奇死亡瘪匿,死狀恐怖,靈堂內(nèi)的尸體忽然破棺而出寻馏,到底是詐尸還是另有隱情棋弥,我是刑警寧澤,帶...
    沈念sama閱讀 36,580評論 5 351
  • 正文 年R本政府宣布诚欠,位于F島的核電站顽染,受9級特大地震影響,放射性物質(zhì)發(fā)生泄漏轰绵。R本人自食惡果不足惜粉寞,卻給世界環(huán)境...
    茶點(diǎn)故事閱讀 42,259評論 3 336
  • 文/蒙蒙 一、第九天 我趴在偏房一處隱蔽的房頂上張望左腔。 院中可真熱鬧唧垦,春花似錦、人聲如沸液样。這莊子的主人今日做“春日...
    開封第一講書人閱讀 32,750評論 0 25
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽。三九已至坊秸,卻和暖如春麸祷,著一層夾襖步出監(jiān)牢的瞬間,已是汗流浹背褒搔。 一陣腳步聲響...
    開封第一講書人閱讀 33,867評論 1 274
  • 我被黑心中介騙來泰國打工阶牍, 沒想到剛下飛機(jī)就差點(diǎn)兒被人妖公主榨干…… 1. 我叫王不留,地道東北人站超。 一個(gè)月前我還...
    沈念sama閱讀 49,368評論 3 379
  • 正文 我出身青樓荸恕,卻偏偏與公主長得像,于是被迫代替她去往敵國和親死相。 傳聞我的和親對象是個(gè)殘疾皇子融求,可洞房花燭夜當(dāng)晚...
    茶點(diǎn)故事閱讀 45,930評論 2 361

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