Eclipse搭建Spring开发环境

一、软件准备

1. Eclipse, 下载地址:http://www.eclipse.org,可下载3.6版本

2. SpringIde, 有两种安装方法,官网:http://www.springsource.org/node/489

3. Spring Framework: 下载地址:http://www.springsource.org/download (这里使用的是2.5.5,最新为3.0.5)

二、软件安装

1. 安装Eclipse,直接解压到某个目录即可,比如我的:E:\SpringDev\eclipse。(注意:使用Eclipse需要安装Java)

2.安装SpringIDE,这里介绍两种方法,一种在线更新:Help->intall new software,更新地址为:http://springide.org/updatesite

Eclipse搭建Spring开发环境

第二种方法,下载离线包:http://u.115.com/file/f97474c557,或者备份下载。下载之后把它解压到Eclipse安装目录下即可。

3. 将下载的spring-framework-2.5.5-with-dependencies.zip解压。将其中的spring.jar(dist 目录中)、commons-logging.jar(lib\jakarta-commons目录)、log4j-1.2.15.jar(lib \log4j目录)这三个文件复制到的”D:\java\Spring\lib” 目录中,然后在Eclipse中建立一个“Springlib”库,将那三个文件添加进“Springlib”库中。关于如何添加用户库参考:http://www.cnblogs.com/maplye/archive/2006/06/19/429404.html

Eclipse搭建Spring开发环境

这样就完成了基本配置。接下来我们新建一个例子。该例子属于《Spring In Action》书中的第一个例子

三、Spring示例

1. 新建Spring Project,取名为HelloWorld。建好之后我们首先先导入用户库,导入方法参考这里。这时目录结果如下图:

Eclipse搭建Spring开发环境

2. 新建interface: GreetingService:

1 package info.leyond.test; 2 3 public interface GreetingService { 4 public void sayGreeting(); 5 }

3. 实现该接口:

Eclipse搭建Spring开发环境
1 package info.leyond.test;

3 public class GreetingServiceImpl implements GreetingService {
4 private String greeting;

6 public GreetingServiceImpl() {}

8 public GreetingServiceImpl(String greeting) {
9 this.greeting = greeting;
10 }
11 
12 public void sayGreeting() {
13 System.out.println(greeting);
14 }
15 
16 public void setGreeting(String greeting) {
17 this.greeting = greeting;
18 }
19 }
Eclipse搭建Spring开发环境

4.测试程序:

Eclipse搭建Spring开发环境
1 package info.leyond.test; 2 3 import org.springframework.beans.factory.BeanFactory;4 import org.springframework.beans.factory.xml.XmlBeanFactory; 5 import org.springframework.core.io.ClassPathResource; 6 7 public class HelloApp { 8 public static void main(String[] args) throws Exception { 9 BeanFactory factory = 10 new XmlBeanFactory(new ClassPathResource("./info/leyond/test/hello.xml")); 11 12 GreetingService greetingService = 13 (GreetingService) factory.getBean("greetingService"); 14 15 greetingService.sayGreeting(); 16 } 17 }
Eclipse搭建Spring开发环境

5. 注意上面的hello.xml,配置如下:

Eclipse搭建Spring开发环境
1 <?xml version="1.0" encoding="UTF-8"?>
2 <beans xmlns="http://www.springframework.org/schema/beans"
3 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
4 xsi:schemaLocation="http://www.springframework.org/schema/beans
5 http://www.springframework.org/schema/beans/spring-beans-2.0.xsd">

7 <bean id="greetingService"
8 class="info.leyond.test.GreetingServiceImpl">
9 <property name="greeting" value="Buenos Dias!" />
10 </bean>
11 </beans>
Eclipse搭建Spring开发环境

6. 文件已经准备妥当。此刻看看项目中项目名称旁边是否有个S标记。如果没有,右击HelloWorld,在弹出菜单中选择“Add Spring Project Nature”即可。

7.右键HelloWorld,选择properties,然后Spring->bean support->Config Files,如下图配置:

Eclipse搭建Spring开发环境

之后就可以看到hello.xml,以及GreetingServiceImpl.java都挂上了S.

Eclipse搭建Spring开发环境