spring-context.xml的位置

Tom*_*mmy 21 java junit spring

当我在tomcat上运行我的应用程序时,spring-context.xml文件位于

/WEB-inf/spring-context.xml

还行吧.但运行junit测试我必须提供我的spring-test-context.xml的位置,如下所示:

@ContextConfiguration(locations={"classpath:/spring-test-context.xml"})
Run Code Online (Sandbox Code Playgroud)

这种方法的唯一方法是文件位于

/src/spring-context.xml

如何让我的应用程序在同一位置找到我的spring-context文件?那么它适用于junit睾丸并部署在tomcat上?

我尝试了这个,它给了我很多关于没有找到任何豆子的错误,但它没有说它找不到文件..

classpath:/WEB-INF/spring-test-context.xml
Run Code Online (Sandbox Code Playgroud)

Sam*_*nen 39

正如duffymo所暗示的那样,Spring TestContext Framework(TCF)假定字符串位置默认位于类路径中.有关详细信息,请参阅JavaDoc for ContextConfiguration.

但是,请注意,您还可以使用Spring的资源抽象(即使用"file:"前缀)在绝对路径或相对路径中指定文件系统中的资源.您可以在JavaDoc中找到有关Spring的modifyLocations()方法的详细信息AbstractContextLoader.

例如,如果您的XML配置文件位于"src/main/webapp/WEB-INF/spring-config.xml"项目文件夹中,则可以将该位置指定为相对文件系统路径,如下所示:

@ContextConfiguration("file:src/main/webapp/WEB-INF/spring-config.xml")
Run Code Online (Sandbox Code Playgroud)

作为替代方案,您可以将Spring配置文件存储在类路径中(例如src/main/resources),然后通过Spring MVC配置中的类路径引用它们 - 例如:

<context-param>
    <param-name>contextConfigLocation</param-name>
    <param-value>classpath:/spring-config.xml</param-value>
</context-param>

<listener>
    <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
Run Code Online (Sandbox Code Playgroud)

使用这种方法,您的测试配置将如下所示(请注意表示资源位于类路径根目录中的前导斜杠):

@ContextConfiguration("/spring-config.xml")
Run Code Online (Sandbox Code Playgroud)

您可能还会发现参考手册的" 使用XML资源配置上下文"部分很有用.

问候,

山姆

(Spring TestContext Framework的作者)


duf*_*ymo 11

问题是/ WEB-INF不在Web应用程序的CLASSPATH中.但是,/ WEB-INF/classes是.

您的测试问题是您没有在应用服务器中运行,因此默认情况下WEB-INF/classes不是CLASSPATH的一部分.我建议您设置测试,以便WEB-INF/classes位于测试CLASSPATH中,或使用相对或绝对文件路径来查找它们.