繁体   English   中英

如何在Spring中定义contextParameter

[英]how to define contextParameter in Spring

我正在开发一个Web项目,并在Tomcat的context.xml中定义了一些属性,例如路径,应用程序配置的属性值。 当我想编写一些在Web容器外部启动的JUnit测试时,问题就来了,如何定义这些参数? 要明确的是,在我的context.xml(在Tomcat配置目录中)中,我具有:

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

在Spring中,我可以通过以下方式访问它:

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

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

我希望我更清楚:)

尝试使用类似这样的东西:

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

//put tests here

}

编辑:

您还可以指定上下文文件的路径:

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

//put tests here

}

为了使以上建议生效,您需要依赖于弹簧测试模块。

您也可以按旧的方式加载上下文文件。

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

然后按名称获取您的bean。

暂无
暂无

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

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