转自:http://blog.itpub.net/30066956/viewspace-1375249/html
1、Spring配置文件在类路径下面web
在Spring的java应用程序中,通常咱们的Spring的配置文件都是放在放在类路径下面(也即编译后会进入到classes目录下)。spring
如下是个人项目,由于是用maven管理的,因此配置文件都放在“src/main/resources”目录下app

这时候,在代码中能够经过框架
- ApplicationContext applicationContext = new ClassPathXmlApplicationContext("applicationContext.xml");
而后获取相应的bean。
若是代码想用Junit测试框架来测试,则Spring提供了对Junit支持,还能够使用注解的方式:webapp
- @RunWith(SpringJUnit4ClassRunner.class)
- @ContextConfiguration(locations={"classpath:applicationContext.xml"})
只须要在相应的Test类前面加上此两个注解(第二个注解用来指明Spring的配置文件位置),就能够在Junit Test类使用中Spring提供的依赖注入功能。maven
2、Spring配置文件在WEB-INF下面post
固然在作J2EE开发时,有些人习惯把Spring文件放在WEB-INF目录(虽然更多人习惯放在类路径下面)下面;或者有些Spring配置文件是放在类路径下面,而有些又放在测试
WEB-INF目录下面,以下图。

这时候,在代码中就不能够使用ClassPathXmlApplicationContext来加载配置文件了,而应使用FileSystemXmlApplicationContext。
- ApplicationContext applicationContext = new FileSystemXmlApplicationContext("src/main/webapp/WEB-INF/applicationContext.xml");
而后获取相应的bean。
若是代码想用Junit测试框架来测试,则Spring提供了对Junit支持,还能够使用注解的方式:
- @RunWith(SpringJUnit4ClassRunner.class)
- @ContextConfiguration(locations={"file:src/main/webapp/WEB-INF/applicationContext.xml"})
只须要在相应的Test类前面加上此两个注解(第二个注解用来指明Spring的配置文件位置),就能够在Junit Test类使用中Spring提供的依赖注入功能。
下面是个人一个Spring管理下的Junit测试类:
- package com.sohu.group.service.external;
-
- import java.util.List;
-
- import org.junit.Test;
- import org.junit.runner.RunWith;
- import org.springframework.beans.factory.annotation.Autowired;
- import org.springframework.test.context.ContextConfiguration;
- import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
-
- @RunWith(SpringJUnit4ClassRunner.class)
- @ContextConfiguration({"file:src/main/webapp/WEB-INF/applicationContext.xml"})
- public class SuFriendServiceImplOverRMITest {
-
- @Autowired
- private SuFriendService suFriendService;
-
- @Test
- public void getUserFollowerListTest(){
- List list = suFriendService.getUserFollowerList("liug_talk@163.com");
- System.out.println("------"+list);
- }
- }