2.搭建与测试Spring的开发环境
一.Spring 需要用到的 jar 包 到www.springsource.org/download 下载spring,解压后得到 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 二.Spring 配置文件的模板 模板可以从Spring的参考手册或是Spring的例子中得到。配置文件的名字可以任意,文件可以存放在任何目录下,但是考虑到通用性,一般放在类路径下。
如果的名称需要用到特殊字符的话,则可以使用name属性,而不使用id属性
三.实例化Spring容器 方法一:在类路径下寻找配置文件来实例化容器(常用)
ApplicationgContext ctx = new ClassPathXmlApplicationContext(new String[]{"beans.xml"});
方法二: 在文件系统路径下寻找配置文件来实例化容器(较少用)
ApplicationContext ctx = new FileSystemXmlApplicationContext(new String[]{"d:\\beans.xml"});
Spring的配置文件可以指定多个,可以通过String数组传入。
四. JUit4 测试用例
package junit.test;
import org.junit.BeforeClass;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import com.spring.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();
}
}
五.手动添加schema文件(Spring配置文件时,不能出现帮助信息的解决方法): windows->preferences->myeclipse->files editors->xmlcatalog 点"add" ,在出现的窗口中的Key Type中选择URI,在location中选"File system",然后在Spring解压目录的dist/resources目录中选择spring-beans-2.5.xsd,回到设置窗口的时候不要急着关闭窗口,应把窗口中的Key Type改为Schema location , Key 改为http://www.springframework.org/schema/beans/spring-beans-2.5.xsd