Manoj
Manoj

Reputation: 5867

What is the difference between grouping config via @import and @ContextConfiguration.?

What is the difference between below two ways of loading configuration.

  1. Two independent config classes are loaded via @ContextConfiguration in test class.

  2. Import one config into another config and load the single into @ContextConfiguration in test class.

I thought both pushes the configuration into the common pool. But i see a difference. I have two global interceptor one is in java.config and another in xml.config. If i follow 2nd approach above, both interceptors are loading.

But if i follow 1st approach, only one interceptor is loading based on whether i'm invoking xml based gateway or java based gateway.

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

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

Updated:

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

Upvotes: 3

Views: 1147

Answers (1)

Sam Brannen
Sam Brannen

Reputation: 31278

If you follow approach #1, both interceptors are actually being loaded... just in different ApplicationContexts.

@ContextHierarchy instructs the Spring TestContext Framework to load a hierarchy of contexts.

Thus, the two configuration setups you have are not identical with regard to contexts. When you use @ContextHierarchy, the XML components can only see other beans defined in the XML ApplicationContext (i.e., the top level of the hierarchy); whereas, the Java DSL components can see all components (i.e., those configured in Java Config and those configured in XML, since the XML context is the parent of the Java Config context).

I believe this is actually what you want...

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

If you don't want SpringConfiguration to import the XML config, you can alternatively use the following to achieve the same behavior:

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration
public class SampleTest {

    @Configuration
    @Import(SpringConfiguration.class)
    @ImportResource("/applicationContext.xml")
    static class Config {}

/* ... */

}

Regards,

Sam (author of the Spring TestContext Framework)

Upvotes: 3

Related Questions