【问题标题】:In Spring does a ContextConfiguration(...) inherit from its parent @ContextConfiguration?在 Spring 中,ContextConfiguration(...) 是否从其父 @ContextConfiguration 继承?
【发布时间】:2016-03-24 00:43:13
【问题描述】:

假设我有一个像这样的父测试类:

@ContextConfiguration(loader = AnnotationConfigContextLoader.class, classes = { MyCustomTestConfig.class })
public class MyParentTestclass {

然后我有一个子类,我想在其中添加Spring 3.2.3 name annotation attribute

@ContextConfiguration(name=MyName)
public class MyChildTestClass extends MyParentTestClass {

我仍然想从父级获取所有上下文配置 - 但不确定它是否会通过。

我的问题是:在 Spring 中 ContextConfiguration(...) 是否从其父级 @ContextConfiguration 继承?

【问题讨论】:

    标签: java spring spring-mvc junit


    【解决方案1】:

    @ContextConfiguration确实支持开箱即用的继承。

    @ContextConfiguration 有一个名为inheritLocations 的属性,默认为true,并指示是否应继承来自测试超类的资源位置或注释类。

    inheritLocations = true:这意味着带注释的类将继承测试超类定义的资源位置或带注释的类。具体来说,给定测试类的资源位置或注释类将附加到由测试超类定义的资源位置或注释类列表中。因此,子类可以选择扩展资源位置列表或带注释的类。

    如果将inheritLocations 设置为false,则注释类的资源位置或注释类将隐藏并有效替换超类定义的任何资源位置或注释类。

    在以下使用带注释的类的示例中,ExtendedTest 的 ApplicationContext 将从 BaseConfig 和 ExtendedConfig 配置类中按顺序加载。因此,在 ExtendedConfig 中定义的 Bean 可能会覆盖在 BaseConfig 中定义的那些。

     @ContextConfiguration(classes=BaseConfig.class)
     public class BaseTest {
         // ...
     }
    
     @ContextConfiguration(classes=ExtendedConfig.class)
     public class ExtendedTest extends BaseTest {
         // ...
     }
    

    【讨论】:

    • 查看 org.springframework.test.context.ContextHierarchy 中的文档
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-06-28
    • 1970-01-01
    • 1970-01-01
    • 2016-04-08
    • 1970-01-01
    相关资源
    最近更新 更多