---
title: "spring环境搭建与测试"
author: "freewxy"
date: "2011-08-10T08:40:37Z"
tags: []
categories: ["编程语言"]
slug: "spring"
draft: false
lastmod: "2011-08-10T08:44:02Z"
id: 1144157
url: "https://freewxy.iteye.com/blog/1144157"
---

**Chapter1、搭建与测试spring的环境**

1、  将必要的jar包导入到新建的project中（可以去官网下载，也可以google或者百度）至少必须使用的有spring.jar 和commons-logging.jar

 

2、  在calsspath路径下创建配置文件beans.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-2.5.xsd">
          <bean id="" class=""></bean>
</beans>
```

 

 

 

 3、  实例化spring容器：

   实例化Spring容器的两种方式：

（1）在类路径下寻找配置文件来实例化容器

ApplicationContext ctx = new ClassPathXmlApplicationXContext(new String\[]{“beans.xml”})

    （2）在文件系统路径下寻找配置文件来实例化容器

ApplicationContext ctx = new FileSystemXmlApplication(new String\[]{“d:\\\\beans.xml”});

Spring 的配置文件可以指定多个，可以通过String数组传入，也可以是一个String

```
public class Test {

    public static void main(String[] args) {
        //IOC容器实例化
        ApplicationContext ctx = new ClassPathXmlApplicationContext("beans.xml");

    }

}
```

 

 

 

  运行测试，结果如下：  
![](http://dl.iteye.com/upload/attachment/533682/1574f8fe-5b11-38e5-91c2-812bdbd38dc0.jpg)

Spring环境搭建成功！

4、创建业务bean接口 ：

```
package com.wxy.service;

public interface PeopleService {

    public abstract void save();

}
```

 

 

5、实现业务bean接口：

```
package com.wxy.service.impl;

import com.wxy.service.PeopleService;

public class PeopleServiceBean implements PeopleService {

    /* (non-Javadoc)
     * @see com.wxy.service.impl.PeopleService#save()
     */
    public void save() {
        System.out.println("--> the method is called save()!");
    }

}
```

 

 

 

 

6、  在beans.xml中配置业务bean，将bean交给spring容器管理，spring创建和维护该bean，用户使用时，只需要获取就可以了，不用自己创建，实现IoC

依赖倒置。

```
<?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-2.5.xsd">
          <bean id="peopleService" class="com.wxy.service.impl.PeopleServiceBean"></bean>
</beans>

```

 

 

 

7、 使用业务bean：

```
public class Test {

    public static void main(String[] args) {
        //IOC容器实例化
        ApplicationContext ctx = new ClassPathXmlApplicationContext("beans.xml");
        //获取业务bean
        PeopleServiceBean peopleService = (PeopleServiceBean) ctx.getBean("peopleService");
        peopleService.save();
    }

}
```

 

 

调用结果：  
![](http://dl.iteye.com/upload/attachment/533680/aec5092d-146d-3402-8d8b-e44f96c63c96.jpg)