简体   繁体   中英

how to define contextParameter in Spring

I am working on a web project and I defined some properties in the context.xml of my Tomcat, like path, properties value for the configuration of the application. My problem arrives when I want to write some JUnit tests, which are launched outside my web container, how can I define these parameters? To be clear, in my context.xml (in Tomcat configuration directory), I have:

<Parameter name="myProperty" value="myValue" override="false"/>

And with Spring, I access it with:

<property name="property" value="#{myProperty}" />

But when I launch a junit test, the context.xml is not loaded, I need another way to define the property. How can I do that? To be more precise, the context.xml file which we are talking about is a file used by my Tomcat server, it does not follow the Spring schema and I think that I can't "import" it into Spring. I already use the SpringJUnit4ClassRunner and the ContextConfiguration tag, it works fine, but now, I need to emulate/replace the Tomcat's behaviour to define this ContextParameters and retrieve my parameter...

I hope I am clearer :)

Try using something like this :

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration("classpath:context.xml")
public class MyTestClass {

//put tests here

}

EDIT:

You can also specify a path to the context file :

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration("file:src/main/resources/spring/config.xml")
public class MyTestClass {

//put tests here

}

For the suggestion above to work, you need to depend on the spring-test module.

You can also load your context file the good old fashion way.

ApplicationContext context = new ClassPathXmlApplicationContext("context.xml")

And then grab your bean by name.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM