【问题标题】:Spring: Can not find applicationContext even though it's present in war fileSpring:即使它存在于war文件中也找不到applicationContext
【发布时间】:2014-09-08 14:23:27
【问题描述】:

我的测试看起来像

public class ITCache extends AbstractIntegrationTest {
    @Test
    public void readCache() {
        ApplicationContext applicationContext = new ClassPathXmlApplicationContext("applicationContext.xml");
        assertNotNull(applicationContext);
        final SimpleCacheManager simpleCacheManager = (SimpleCacheManager) applicationContext.getBean("cacheManager");
        System.out.println("cacheName:" + simpleCacheManager.getCacheNames().toString());
        System.out.println(simpleCacheManager.getCache("genders").toString());
    }
}

我使用maven-cargo插件部署我的项目,可以看到内容并找到applicationContext.xml

➜  comma git:(S120297) ✗ jar -tvf integration/target/cargo/configurations/tomcat7x/webapps/common.war | grep app
  2342 Wed Jul 16 20:28:32 PDT 2014 WEB-INF/classes/applicationContext.xml
➜  comma git:(S120297) ✗  

但是当我运行测试时,我认为失败是

Tests in error: 
  readCache(com.org.comma.integration.ITCache): IOException parsing XML document from class path resource [applicationContext.xml]; nested exception is java.io.FileNotFoundException: class path resource [applicationContext.xml] cannot be opened because it does not exist  

我还尝试将我的测试注释为

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration (locations = "classpath*:/applicationContext*.xml")
public class ITCache extends AbstractIntegrationTest {  

但还是同样的问题

这里出了什么问题?

更新
我的web.xml 有以下条目

    <context-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>classpath:applicationContext.xml</param-value>
    </context-param>
    <listener>
        <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
    </listener>

【问题讨论】:

  • applicationContext.xml 必须在 WEB-INF 文件夹中。你确定不在吗?
  • 我的问题中提到的WEB-INF/classes/applicationContext.xml
  • 尝试将文件放在WEB-INF文件夹中,以便有WEB-INF/applicationContext.xml
  • 好的,如何将 applicationContext.xml 放入该文件夹?当您的测试运行时,它不会针对打包的 webapp 运行,而是针对类路径运行,并在构建期间复制到 WEB-INF/classes。但是,如果 applicationContext.xml 位于资源文件夹的根目录中,则会在类路径中找到它。但是,如果您手动将它放在源代码的 WEB-INF/classes 中,那么您就是 SOL——它不会出现在您的测试的类路径中。
  • @DarkCoffee——这行不通。它需要在类路径中,而不是在 WEB-INF...

标签: java spring maven maven-cargo


【解决方案1】:

正如错误所说,在您的类路径中找不到该文件,请确保您的文件位于类路径的根目录中,您可以将 applicationContext 文件添加到资源文件夹并启动安装。 我有相同的代码并且它可以工作,web.xml 与启动测试无关,启动测试的其他事情很重要,你可以使用 Maven 或直接使用 Eclipse 来完成。我们使用 Maven 启动测试,它生成的资源与其他方式不同。

【讨论】:

    猜你喜欢
    • 2018-12-21
    • 2019-07-26
    • 1970-01-01
    • 2015-10-26
    • 2022-07-12
    • 2014-02-20
    • 2014-05-16
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多