在Spring3.0中我使用AbstractTransactionalJUnit38SpringContextTests来作为测试类的父类.
使用@ContextConfiguration来读取配置文件.
我的配置文件在/WEB-INF/config/spring/applicationContext.xml.
在web.xml中写
<context-param> <param-name>contextConfigLocation</param-name> <param-value>/WEB-INF/config/spring/applicationContext.xml</param-value> </context-param>
没问题,可以读到.
但是在测试类中写
@ContextConfiguration("/WEB-INF/config/spring/applicationContext.xml")
就会报错,class path resource [WEB-INF/config/spring/applicationContext.xml] cannot be opened because it does not exist
这是因为他是默认从classpath中读配置文件,但是我的配置文件不在classpath下.
好,改成这样写
@ContextConfiguration("file:WebContent/WEB-INF/config/spring/applicationContext.xml")
applicationContext.xml可以读到了.
但是我还配置了IBatis的sqlMapClient,要读配置文件/WEB-INF/config/ibatis/SqlMapConfig.xml.
原来在Spring的配置文件里,这样写,
<bean id="sqlMapClient" class="org.springframework.orm.ibatis.SqlMapClientFactoryBean" p:configLocation="/WEB-INF/config/ibatis/SqlMapConfig.xml" p:dataSource-ref="dataSource" />
没问题,可以读到,但是@ContextConfiguration里不行,
同样是报class path resource [WEB-INF/config/ibatis/SqlMapConfig.xml] cannot be opened because it does not exist.
好吧,我再改成
<bean id="sqlMapClient" class="org.springframework.orm.ibatis.SqlMapClientFactoryBean" p:configLocation="file:WebContent/WEB-INF/config/ibatis/SqlMapConfig.xml" p:dataSource-ref="dataSource" />
OK,都读的到了,可以进行测试了.
但是,正常启动服务器时,读取配置文件时,
却报错,java.io.FileNotFoundException: WebContent\WEB-INF\config\ibatis\SqlMapConfig.xml (The system cannot find the path specified).
如果写完整路径,即"盘符+路径"是可以读到的,这样明显不现实.
发现测试是用org.springframework.test.context.support.AbstractContextLoader来读取配置文件的,难道做过什么优化?
所以,我的问题是,我的所有配置文件都没放在classpath下,我该怎么写,才能保证启动服务器和进行测试时都能读的到?