您的位置:首页 > 编程语言 > Java开发

搭建与测试Spring的开发环境

2009-11-22 18:26 501 查看
1.关键lib包

shttp://www.springsource.org/downloads/下载spring,然后进行解压缩,在解压目录中找到下面jar文件,拷贝到类路径下

dist/spring.jar
lib/jakarta-commons/commons-logging.jar

如果使用了切面编程(AOP),还需要下列jar文件
lib/aspectj/aspectjweaver.jar和aspectjrt.jar
lib/cglib/cglib-nodep-2.1_3.jar

如果使用了JSR-250中的注解,如@Resource/@PostConstruct/@PreDestroy,还需要下列jar文件
lib/j2ee/common-annotations.jar

2.配置模版

<?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="persionServiceBean" class="cn.itcast.service.implement.PersionServiceBean"></bean>

</beans>

该配置模版可以从spring的参考手册或spring的例子中得到。配置文件的取名可以任意,文件可以存放在任何目录下,但考虑到通用性,一般放在类路径下。

小技巧: 此配置文件在eclipse 中会有提示标签的功能,那是因为eclipse会连接互联网找到相应的文件,因此由了提示功能,如果你的机器没有联网,或者没有提示标签的功能,你可以这样做

windows-preferences->web and xml ->xml catalog-> add->定位到spring-beans-2.5.xsd文件在硬盘中的位置(H:/电脑软件/java工具/spring-framework-2.5.6-with-dependencies/spring-framework-2.5.6/dist/resources/spring-beans-2.5.xsdspring-beans-2.5.xsd) -> KeyType 选择 schema Localtion -> key 本来是:http://www.springframework.org/schema/beans 在后面加上spring-beans-2.5.xsd ->OK

一个入门的小例子:

spring 强调我们面向接口编程,我们可以先写业务方法的实现类,在其中写业务方法,然后抽取接口,注意接口和接口的实现不要在一个包下.

例如:

接口实现: PersionServiceBean

package cn.itcast.service.implement;

import cn.itcast.service.PersonService;

public class PersonServiceBean implements PersonService {

/* (non-Javadoc)
* @see cn.itcast.service.implement.PersonService#save()
*/
public void save(){
System.out.print("我是save()方法");
}

}


在这个类右肩点击 Refactor ->Extract InterFace(抽取接口) ->写接口的名字->选择save方法,eclipse会帮助我们根据业务类的实现方法抽取接口. -> 在接口上 右键 Refactor -> move 把接口移动到接口包中

接口: PersionSevice

package cn.itcast.service;

public interface PersonService {

public abstract void save();

}


测试例子:

/**
*
*/
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;

/**
* @author Administrator
*
*/
public class SpringTest {

/**
* @throws java.lang.Exception
*/
@BeforeClass
public static void setUpBeforeClass() throws Exception {//spring 面向接口编程
}
@Test public void instanceSpring() {
ApplicationContext ctx = new ClassPathXmlApplicationContext("beans.xml");//首先找到beans.xml配置文件
PersonService personService = (PersonService)ctx.getBean("personService");//调用<bean id="personService" class=""></bean>,找到那个bean
personService.save();//调用PersonService里的save方法
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: