【慕課網Spring系列學習攻略】IOC及Bean容器篇


從慕課網的java工程師路徑一路學上來,感覺很順利,但鑑於Spring系列對新手不太友好,寫點我的理解希望對新手有點幫助!

慕課網地址:http://www.imooc.com/learn/196


1、搭建環境

由於老師用的環境比較複雜,我們暫時不需要那麼複雜的環境,可以先搭建一個簡單點的!注重對知識的學習即可:


在eclipse中新建web工程:




填入項目名,點擊呢next->next,生成web.xml打勾,完成:


引入jar包,除了老師所給的spring1、2外還需要引入junit-4.10.jar包和commons-logging-1.1.jar

可以從我的百度雲下載:http://pan.baidu.com/s/1mijRa2W


這樣就可以開始學習了。


2、創建接口及實現


在Java Resources/src新建新建一個包com.imooc.ioc.interfaces,並在包裏新建一個接口OneInterface和一個實現OneInterfaceImpl:

package com.imooc.ioc.interfaces;

public interface OneInterface {
	
	public void say(String word);
	
}
package com.imooc.ioc.interfaces;

public class OneInterfaceImpl implements OneInterface {
	
	public void say(String word) {
		return "Word from interface \"OneInterface\":"+word;
	}

}
在Java Resources/src下新建一個spring配置文件spring-ioc.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="oneinterface" class="com.imooc.ioc.interfaces.OneInterfaceImpl"></bean>
</beans> 
之後就可以創建一個測試類來驗證我們配置的正確性了。在com.imooc.ioc.interfaces中新建一個Main類:


老師視頻中用的父類UnitTestBase是自己自定義的,我們需要用的前面junit中學到的知識自己寫個簡單點的測試方法:

package com.imooc.ioc.interfaces;

import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class Main {
    private ClassPathXmlApplicationContext ctx;

    @Before
    public void init(){
        ctx = new ClassPathXmlApplicationContext("spring-ioc.xml");
        ctx.start();
    }
    @Test
    public void testHello(){
        OneInterface oneinterface = (OneInterface)ctx.getBean("oneinterface");
        System.out.println(oneinterface.say("我的輸入參數"));
    }
    @After
    public void detroy(){
        ctx.destroy();
    }

}

這樣就可以運行Junit測試了,整體預覽:



運行:



結果:



這樣大體實現了老師的功能。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章