【问题标题】:What is the difference between grouping config via @import and @ContextConfiguration.?通过@import 和@ContextConfiguration 对配置进行分组有什么区别?
【发布时间】:2015-10-16 09:17:27
【问题描述】:

以下两种加载配置的方式有什么区别。

  1. 两个独立的配置类通过测试类中的@ContextConfiguration 加载。

  2. 将一个配置导入另一个配置,并将单个配置加载到测试类中的@ContextConfiguration。

我认为两者都将配置推送到公共池中。但我看到了不同。我有两个全局拦截器,一个在 java.config 中,另一个在 xml.config 中。如果我按照上面的第二种方法,两个拦截器都在加载。

但是如果我遵循第一种方法,则只有一个拦截器正在加载,具体取决于我是调用基于 xml 的网关还是基于 java 的网关。

https://github.com/manojp1988/Learning/tree/JavaDSL/Sample1

@RunWith(SpringJUnit4ClassRunner.class)
@ContextHierarchy({
 @ContextConfiguration(locations = {"/applicationContext.xml"}),
 @ContextConfiguration(classes = SpringConfiguration.class),
 })
public class SampleTest {}

更新:

@Bean
  @GlobalChannelInterceptor(patterns = "*_EL*", order=3)
  public WireTap wireTap() {

【问题讨论】:

    标签: spring spring-integration spring-test


    【解决方案1】:

    如果您遵循方法#1,两个拦截器实际上都在被加载...只是在不同ApplicationContexts

    @ContextHierarchy 指示 Spring TestContext 框架 加载一个层次结构的上下文。

    因此,您拥有的两个配置设置在上下文方面并不相同。当您使用@ContextHierarchy 时,XML 组件只能看到 XML 中定义的其他 bean ApplicationContext(即层次结构的顶层);而 Java DSL 组件可以看到所有组件(即在 Java Config 中配置的组件在 XML 中配置的组件,因为 XML 上下文是 Java Config 上下文的 parent )。

    我相信这实际上是你想要的......

    @RunWith(SpringJUnit4ClassRunner.class)
    @ContextConfiguration(classes = SpringConfiguration.class)
    public class SampleTest { /* ... */ }
    
    @Configuration
    @ComponentScan(basePackages = "com.model")
    @EnableIntegration
    @IntegrationComponentScan
    @ImportResource("/applicationContext.xml")
    public class SpringConfiguration { /* ... */ }
    

    如果您不希望 SpringConfiguration 导入 XML 配置,您也可以使用以下方法来实现相同的行为:

    @RunWith(SpringJUnit4ClassRunner.class)
    @ContextConfiguration
    public class SampleTest {
    
        @Configuration
        @Import(SpringConfiguration.class)
        @ImportResource("/applicationContext.xml")
        static class Config {}
    
    /* ... */
    
    }
    

    问候,

    Sam(Spring TestContext 框架的作者

    【讨论】:

    • 谢谢山姆。但是,如果您说我班级中的 java config 知道 XML 和 Java 中的配置,那么为什么 xml 拦截器在我调用时不起作用。 hello.sayHello("Manoj")。从 Java 配置加载的上下文应该具有正确的 XML 配置和 Java 配置?
    • 使用存储库中的当前代码,您创建上下文层次结构,因此 XML 拦截器确实拦截“Manoj”消息:@ 987654330@ 输出XML Intecepted Manoj / DSL InterceptedManoj / XML Intecepted Jeeva / Hello Jeeva / DSL InterceptedJeeva
    • 如果你遵循方法#1——正如我之前提到的——你实际上是在创建两个上下文,并且XML拦截器看不到子上下文中的流。
    • 因此,仅仅通过在@contextheirarchy 中定义配置,我们不能期望它会全部加载到单个上下文中。我们需要将一个配置导入另一个。我的应用程序中需要多个上下文的目的可能是什么?
    • 没错。 @ContextHierarchy 的重点是加载多个上下文并在父子上下文的层次结构中配置它们。有关详细信息,请参阅参考手册的Context hierarchies 部分。参考手册中还概述了层次结构的典型用例。
    猜你喜欢
    • 2022-01-07
    • 2013-02-02
    • 1970-01-01
    • 2020-07-23
    • 2017-04-20
    • 2013-10-08
    • 1970-01-01
    相关资源
    最近更新 更多