`
coolszy
  • 浏览: 1407101 次
  • 性别: Icon_minigender_1
  • 来自: 南京
社区版块
存档分类
最新评论

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

阅读更多

 开始接触Spring了,写下笔记方便以后使用。

 

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

 

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

 

在Myeclipse中创建Java项目。

 

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

package com.szy.spring.interfacebean;

public interface PersonBean
{
	void show();
}

 然后写一个类实现这个接口。

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 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"
	xmlns:tx="http://www.springframework.org/schema/tx"
	xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd
				http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-2.5.xsd
				http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-2.5.xsd">

</beans>

 

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

<bean id="userBean" class="com.szy.spring.implbean.UserBean" />

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

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

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

	<bean id="userBean" class="com.szy.spring.implbean.UserBean" />
</beans>

 

 

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

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

 

Ok,我们的第一个Spring程序成功运行。

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics