【问题标题】:Overriding ContextHierarchy and ContextConfiguration from a meta-annotation从元注释覆盖 ContextHierarchy 和 ContextConfiguration
【发布时间】:2014-07-31 17:58:33
【问题描述】:

我们有使用元注释的测试类:

@WebAppConfiguration
@ContextHierarchy({
    @ContextConfiguration(locations = {"/web/WEB-INF/spring.xml" }, name = "parent"),
    @ContextConfiguration("/web/WEB-INF/spring-servlet.xml")
})
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
public @interface BaseSpringTest {
}

但希望能够从测试类本身覆盖或附加到层次结构的元素,例如:

@BaseSpringTest
@ContextConfiguration(locations = {"/web/WEB-INF/spring-extension.xml" }, name = "parent")
public class MyTest extends AbstractTestNGSpringContextTests {
    ...
}

到目前为止,这对我们还没有奏效...是否有任何机制可以做到这一点?我找到了https://jira.spring.io/browse/SPR-11038,但我认为这不是解决这种情况的方法。

谢谢!

【问题讨论】:

  • 请注意,如果您发现您的问题的答案之一可以接受,请随时accept it

标签: java spring spring-test spring-test-mvc


【解决方案1】:

是否有任何机制来实现这一点?

不,没有支持这种配置风格的机制。

自定义组合注释可以代替实际注释使用,不能与实际注释结合使用。在整个核心 Spring 框架中都是如此(可能@Profile@Conditional 除外)。

换句话说,你不能在同一个类上声明@ContextConfiguration 和另一个使用@ContextConfiguration 元注释的注释(例如,你的@BaseSpringTest)。如果你这样做了,你会发现 Spring 只找到其中​​一个声明。

但是,如果您引入一个基类,您可以实现您的目标(尽管需要扩展该基类):

@BaseSpringTest
public abstract class AbstractBaseTests extends AbstractTestNGSpringContextTests {
    // ...
}

@ContextConfiguration(locations = {"/web/WEB-INF/spring-extension.xml" }, name = "parent")
public class MyTest extends AbstractBaseTests {
    // ...
}

当然,如果您要走“基类”路线,自定义组合注释可能对您没有那么有用。

问候,

Sam(Spring TestContext 框架的作者)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-12-08
    • 1970-01-01
    • 2011-10-28
    • 1970-01-01
    • 2012-02-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多