读书人

Spring学习札记(1)-简单的实例

发布时间: 2012-11-01 11:11:33 作者: rapoo

Spring学习笔记(1)----简单的实例

Spring学习笔记(1)----简单的实例
开始接触Spring了,写下笔记方便以后使用。



首先需要准备Spring包,可从官方网站上下载。



下载解压后,必须的两个包是spring.jar和commons-logging.jar。此外为了便于测试加入了JUnit包。



在Myeclipse中创建Java项目。



编写一个接口类,为了简单,只加入了一个方法。

Java代码
package com.szy.spring.interfacebean;??
?
public interface PersonBean??
{??
??? void show();??
}?

package com.szy.spring.interfacebean;

public interface PersonBean
{
void show();
}
然后写一个类实现这个接口。

Java代码
package com.szy.spring.implbean;??
import com.szy.spring.interfacebean.PersonBean;??
?
public class UserBean implements PersonBean??
{??
?
??? public void show()??
??? {??
??????? System.out.println("Hello Kuka");??
??? }??
?
}?

package com.szy.spring.implbean;
import com.szy.spring.interfacebean.PersonBean;

public class UserBean implements PersonBean
{

public void show()
{
System.out.println("Hello Kuka");
}

}




以上的过程我们再熟悉不过了,下面开始加入Spring的内容了。首先从下载的Sping包中找到配置文件,删除不需要的,找到最原始的部分:

Xml代码



我们在配置文件中加入我们的bean信息

Xml代码
其中id作为标识符,class为类的包路径。

这样我们的配置文件就写好了,完整的配置文件呢如下。

Xml代码





最后我们创建一个测试类测试:

Java代码
package com.szy.spring.test;??
?
import org.junit.Test;??
import org.springframework.context.ApplicationContext;??
import org.springframework.context.support.ClassPathXmlApplicationContext;??
import com.szy.spring.interfacebean.PersonBean;??
?
?
public class TestClass??
{??
??? @Test?
??? public void testMethod() throws Exception??
??? {??
??????? //读取配置文件??
??????? ApplicationContext ctx=new ClassPathXmlApplicationContext("applicationContext.xml");??
??????? //获取UserBean的实例??
??????? PersonBean bean=(PersonBean)ctx.getBean("userBean");??
??????? //调用方法??
??????? bean.show();??
??? }??
}?

package com.szy.spring.test;

import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import com.szy.spring.interfacebean.PersonBean;


public class TestClass
{
@Test
public void testMethod() throws Exception
{
//读取配置文件
ApplicationContext ctx=new ClassPathXmlApplicationContext("applicationContext.xml");
//获取UserBean的实例
PersonBean bean=(PersonBean)ctx.getBean("userBean");
//调用方法
bean.show();
}
}




运行,输入如下结果:

结果代码
Hello Kuka?

?

读书人网 >软件架构设计

热点推荐