Chinaunix首页 | 论坛 | 博客
  • 博客访问: 2505957
  • 博文数量: 319
  • 博客积分: 9650
  • 博客等级: 中将
  • 技术积分: 3881
  • 用 户 组: 普通用户
  • 注册时间: 2009-03-27 21:05
文章分类

全部博文(319)

文章存档

2017年(5)

2016年(10)

2015年(3)

2014年(3)

2013年(10)

2012年(26)

2011年(67)

2010年(186)

2009年(9)

分类: Java

2010-06-02 19:55:23

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

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

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

 

在Myeclipse中创建Java项目。

 

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

Java代码
  1. package com.szy.spring.interfacebean;   
  2.   
  3. public interface PersonBean   
  4. {   
  5.     void show();   
  6. }  

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

Java代码
  1. package com.szy.spring.implbean;   
  2. import com.szy.spring.interfacebean.PersonBean;   
  3.   
  4. public class UserBean implements PersonBean   
  5. {   
  6.   
  7.     public void show()   
  8.     {   
  9.         System.out.println("Hello Kuka");   
  10.     }   
  11.   

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

Xml代码
  1. xml version="1.0" encoding="UTF-8"?>  
  2. <beans xmlns=""  
  3.     xmlns:xsi=""  
  4.     xmlns:context=""  
  5.     xmlns:tx=""  
  6.     xsi:schemaLocation=" /spring-beans-2.5.xsd   
  7.                  /spring-context-2.5.xsd   
  8.                  /spring-tx-2.5.xsd">  
  9.   
  10. beans>  

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

Xml代码
  1. <bean id="userBean" class="com.szy.spring.implbean.UserBean" />  

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

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

Xml代码
  1. xml version="1.0" encoding="UTF-8"?>  
  2. <beans xmlns=""  
  3.     xmlns:xsi=""  
  4.     xmlns:context=""  
  5.     xmlns:tx=""  
  6.     xsi:schemaLocation=" /spring-beans-2.5.xsd   
  7.                  /spring-context-2.5.xsd   
  8.                  /spring-tx-2.5.xsd">  
  9.   
  10.     <bean id="userBean" class="com.szy.spring.implbean.UserBean" />  
  11. beans>  

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

Java代码
  1. package com.szy.spring.test;   
  2.   
  3. import org.junit.Test;   
  4. import org.springframework.context.ApplicationContext;   
  5. import org.springframework.context.support.ClassPathXmlApplicationContext;   
  6. import com.szy.spring.interfacebean.PersonBean;   
  7.   
  8.   
  9. public class TestClass   
  10. {   
  11.     @Test  
  12.     public void testMethod() throws Exception   
  13.     {   
  14.         //读取配置文件   
  15.         ApplicationContext ctx=new ClassPathXmlApplicationContext("applicationContext.xml");   
  16.         //获取UserBean的实例   
  17.         PersonBean bean=(PersonBean)ctx.getBean("userBean");   
  18.         //调用方法   
  19.         bean.show();   
  20.     }   
  21. }  

运行,输入如下结果:

结果代码
  1. Hello Kuka  

 

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

  • (2.6 MB)
阅读(941) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~