【慕课网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测试了,整体预览:



运行:



结果:



这样大体实现了老师的功能。

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