随笔-21  评论-29  文章-0  trackbacks-0
搭建与测试Spring的开发环境
使用版本为Spring2.5.6

新建一个Java Project 命名为spring 并导入相关的jar包
配置Spring配置文件

在src下新建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"
>
          
</beans>

实例化Spring容器 建议用方法一

新建一个单元测试SpringTest,并导入测试所用的包
package junit.test;
import org.junit.BeforeClass;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import cn.itcast.service.PersonService;

public class SpringTest {

    @BeforeClass
    public static void setUpBeforeClass() throws Exception {
    }

    @Test public void instanceSpring(){
        ApplicationContext ctx = new ClassPathXmlApplicationContext("beans.xml");
            }
}

新建一个业务Bean,命名为PersonServiceBean;抽取PersonServiceBean的接口。
package cn.itcast.service.impl;

import cn.itcast.service.PersonService;

public class PersonServiceBean implements PersonService {

    
public void save(){
        System.out.println(
"我是save()方法");
    }

}


package cn.itcast.service;

public interface PersonService {

    
public void save();

}
在配置文件中加入如下语句实现
<bean id="personService" class="cn.itcast.service.impl.PersonServiceBean"></bean>
注意:编写spring配置文件时,不能出现帮助信息 同通过如下方法解决


修改SpringTest代码
package junit.test;
import org.junit.BeforeClass;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import cn.itcast.service.PersonService;

public class SpringTest {

    @BeforeClass
    
public static void setUpBeforeClass() throws Exception {
    }


    @Test 
public void instanceSpring(){
        ApplicationContext ctx 
= new ClassPathXmlApplicationContext("beans.xml");
        PersonService personService 
= (PersonService)ctx.getBean("personService");
        personService.save();
    }

}

在实例化了容器之后,从容器中取得bean,再调用业务bean的save方法

执行SpringTest文件 观察控制台输出



以上证明本Spring程序运行成功!

代码参考 /Files/luckygino/spring.rar
posted on 2009-05-06 10:25 特立独行 阅读(455) 评论(0)  编辑  收藏 所属分类: Spring框架

只有注册用户登录后才能发表评论。


网站导航: