Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Location of spring-context.xml

Tags:

When I run my application on tomcat the spring-context.xml file is located at

/WEB-inf/spring-context.xml

This is ok. But running a junit test I have to supply it with the location of my spring-test-context.xml like this:

@ContextConfiguration(locations={"classpath:/spring-test-context.xml"}) 

The only way this works is if the file is located in

/src/spring-context.xml

How can I get my application to find my spring-context files in the same location? So that it works with junit testes and deployed on tomcat?

I tried this and it gave me alot of errors about not finding any beans, but it didn't say it couldn't find the file..

classpath:/WEB-INF/spring-test-context.xml 
like image 634
Tommy Avatar asked Apr 30 '12 14:04

Tommy


1 Answers

As duffymo hinted at, the Spring TestContext Framework (TCF) assumes that string locations are in the classpath by default. For details, see the JavaDoc for ContextConfiguration.

Note, however, that you can also specify resources in the file system with either an absolute or relative path using Spring's resource abstraction (i.e., by using the "file:" prefix). You can find details on that in the JavaDoc for the modifyLocations() method in Spring's AbstractContextLoader.

So for example, if your XML configuration file is located in "src/main/webapp/WEB-INF/spring-config.xml" in your project folder, you could specify the location as a relative file system path as follows:

@ContextConfiguration("file:src/main/webapp/WEB-INF/spring-config.xml") 

As an alternative, you could store your Spring configuration files in the classpath (e.g., src/main/resources) and then reference them via the classpath in your Spring MVC configuration -- for example:

<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> 

With this approach, your test configuration would simply look like this (note the leading slash that denotes that the resource is in the root of the classpath):

@ContextConfiguration("/spring-config.xml") 

You might also find the Context configuration with XML resources section of the reference manual useful.

Regards,

Sam

(author of the Spring TestContext Framework)

like image 169
Sam Brannen Avatar answered Sep 29 '22 01:09

Sam Brannen