【问题标题】:how to define contextParameter in Spring如何在Spring中定义上下文参数
【发布时间】:2012-07-23 23:30:27
【问题描述】:

我正在开发一个 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 并检索我的参数...

我希望我更清楚:)

【问题讨论】:

标签: spring properties junit


【解决方案1】:

尝试使用这样的东西:

@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

}

【讨论】:

  • 感谢您的回答,但问题是 context.xml 是一个 Tomcat 文件,我无法通过简单地将其添加到我的类路径中来直接引用它。
【解决方案2】:

要使上述建议生效,您需要依赖 spring-test 模块。

你也可以用老式的方式加载你的上下文文件。

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

然后按名称获取您的 bean。

【讨论】:

    猜你喜欢
    • 2013-01-15
    • 2014-12-25
    • 2010-12-10
    • 1970-01-01
    • 1970-01-01
    • 2016-08-15
    • 2011-10-02
    • 2013-02-23
    • 1970-01-01
    相关资源
    最近更新 更多