轉載地址:http://www.mrfeng.net/post/189.html
假設Spring配置文件為applicationContext.xml
一、Spring配置文件在類路徑下面
在Spring的java應用程序中,一般我們的Spring的配置文件都是放在放在類路徑下面(也即編譯后會進入到classes目錄下)。
以下是我的項目,因為是用maven管理的,所以配置文件都放在“src/main/resources”目錄下
這時候,在代碼中可以通過
-
ApplicationContext applicationContext = newClassPathXmlApplicationContext("applicationContext.xml");
然后獲取相應的bean。
如果代碼想用Junit測試框架來測試,則Spring提供了對Junit支持,還可以使用注解的方式:
-
@RunWith(SpringJUnit4ClassRunner.class)
-
@ContextConfiguration(locations={"classpath:applicationContext.xml"})
只需要在相應的Test類前面加上此兩個注解(第二個注解用來指明Spring的配置文件位置),就可以在Junit Test類使用中Spring提供的依賴注入功能。
二、Spring配置文件在WEB-INF下面
當然在做J2EE開發時,有些人習慣把Spring文件放在WEB-INF目錄(雖然更多人習慣放在類路徑下面)下面;或者有些Spring配置文件是放在類路徑下面,而有些又放在
WEB-INF目錄下面,如下圖。
這時候,在代碼中就不可以使用ClassPathXmlApplicationContext來加載配置文件了,而應使用FileSystemXmlApplicationContext。
-
ApplicationContext applicationContext = newFileSystemXmlApplicationContext("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<String> list = suFriendService.getUserFollowerList("liug_talk@163.com");
-
System.out.println("------"+list);
-
}
-
}