简体   繁体   English

如何在Spring中定义contextParameter

[英]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. 我正在开发一个Web项目,并在Tomcat的context.xml中定义了一些属性,例如路径,应用程序配置的属性值。 My problem arrives when I want to write some JUnit tests, which are launched outside my web container, how can I define these parameters? 当我想编写一些在Web容器外部启动的JUnit测试时,问题就来了,如何定义这些参数? To be clear, in my context.xml (in Tomcat configuration directory), I have: 要明确的是,在我的context.xml(在Tomcat配置目录中)中,我具有:

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

And with Spring, I access it with: 在Spring中,我可以通过以下方式访问它:

<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. 但是,当我启动junit测试时,未加载context.xml,我需要另一种定义属性的方法。 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. 更准确地说,我们正在谈论的context.xml文件是我的Tomcat服务器使用的文件,它不遵循Spring架构,我认为我无法将其“导入”到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... 我已经使用过SpringJUnit4ClassRunner和ContextConfiguration标签,它可以正常工作,但是现在,我需要模拟/替换Tomcat的行为以定义此ContextParameters并检索我的参数...

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. 然后按名称获取您的bean。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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