我有一个Maven web项目,我想在其中执行一些JUnit集成测试。为了实现这一点,我想加载applicationContext.xml文件以获得Spring注入的bean。此外,我的应用程序上下文文件位于src/main/resources/app_context
中,但是当执行Maven的生命周期时,它将它们定位到WEB-INF/classes/application_context
中,因此我能够通过类路径访问它们。
<resource>
<directory>src/main/resources/appcontext</directory>
<targetPath>${basedir}/src/main/webapp/WEB-INF/classes/application_context</targetPath>
<filtering>true</filtering>
<includes>
<include>*/**</include>
</includes>
</resource>
我曾试图以某种方式访问那个上下文,但没有成功。我还以这种方式将它们放入Maven的目标测试目录:
<testResources>
<testResource>
<directory>
src/main/resources/appcontext
</directory>
<targetPath>${basedir}/src/main/webapp/WEB-INF/classes/application_context</targetPath>
</testResource>
</testResources>
这是我的一个测试:
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = { "classpath:**/applicationContext.xml" })
@Transactional
public class SystemTest {
@Autowired
ApplicationContext applicationContext;
@Test
public void initializeSystemTest() {
//Test code
这就是我从主文件中访问其他应用程序上下文文件的方式:
<?xml version="1.0" encoding="ISO-8859-15"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:p="http://www.springframework.org/schema/p"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:jee="http://www.springframework.org/schema/jee" xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:cxf="http://cxf.apache.org/core" xmlns:jaxws="http://cxf.apache.org/jaxws"
xsi:schemaLocation="
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.1.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.1.xsd
http://www.springframework.org/schema/jee http://www.springframework.org/schema/jee/spring-jee-3.1.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.1.xsd">
<import resource="classpath:application_context/ApplicationContext*.xml" />
<context:annotation-config />
<!--========== Spring Data Source ========== -->
<!--Bean stuff-->
基本上我想只有一个副本的每一个applicationContext文件存储在src/main/resources
和让Maven复制他们的测试和执行范围。但是,我的测试类无法找到并加载它们。我该怎么做?
假设您的applicationContext.xml
在src/main/resources/appcontext
中,Maven将在默认情况下在WEB-INF/classes/appcontext
中重新分配它。没有必要为该资源分配一个新路径。
您应该能够在您的测试中找到上下文文件:
@ContextConfiguration(locations={"/appcontext/applicationContext.xml"})