关于单元测试时加载spring-context.xml文件的问题

时间:2023-03-08 22:31:22
关于单元测试时加载spring-context.xml文件的问题

在进行web开发的时候,通常我们都会使用Spring框架,使用spring容器管理java bean。 而spring的配置文件有时候放在classpath下面,有时候放在WEB-INF下面。

一般在开发的过程中都需要对开发完的方法进行单元测试,而单元测试需要使用到注解,就需要使用

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations={"classpath:spring-context.xml"})

两个注解加载spring配置文件。

关于spring配置文件路径的写法,如果spring-context.xml文件放在classpath下面,这种写法是对的

但是如果放在了WEB-INF,即不是classpath下,怎么引用呢?

需要从文件系统加载,使用file开头:

@ContextConfiguration(locations={"file:WebRoot/WEB-INF/spring-context.xml"})

就可以加载成功!!!