Spring Junit 读取WEB-INF下的配置文件

假设Spring配置文件为applicationContext.xml

一、Spring配置文件在类路径下面

在Spring的java应用程序中,一般我们的Spring的配置文件都是放在放在类路径下面(也即编译后会进入到classes目录下)。

以下是我的项目,因为是用maven管理的,所以配置文件都放在“src/main/resources”目录下

image

这时候,在代码中可以通过

ApplicationContext applicationContext = new ClassPathXmlApplicationContext("applicationContext.xml");  

如果代码想用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目录下面,如下图。

image

这时候,在代码中就不可以使用ClassPathXmlApplicationContext来加载配置文件了,而应使用FileSystemXmlApplicationContext。

ApplicationContext applicationContext = new FileSystemXmlApplicationContext("src/main/webapp/WEB-INF/applicationContext.xml");    

如果代码想用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);  
    }  
}  
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

  • Spring Cloud为开发人员提供了快速构建分布式系统中一些常见模式的工具(例如配置管理,服务发现,断路器,智...
    卡卡罗2017阅读 136,183评论 19 139
  • Spring Boot 参考指南 介绍 转载自:https://www.gitbook.com/book/qbgb...
    毛宇鹏阅读 47,170评论 6 342
  • 在我搭建基于Spring Cloud的微服务体系应用的时候所需要或者是常用的属性配置文件,还有这些属性的用途,此配...
    StrongManAlone阅读 9,629评论 0 18
  • spring官方文档:http://docs.spring.io/spring/docs/current/spri...
    牛马风情阅读 5,736评论 0 3
  • 明天应该是个好日子 明天应该会奔波一天 明天心中会有些不舍 明天感觉那么的近 又是那么的远 明天就要出发了 带上行...
    赤足者阅读 1,688评论 0 1

友情链接更多精彩内容