@Import vs @ContextConfiguration in Spring

@Import and @ContextConfiguration are for different use cases and cannot be used interchangeability.

The @Import is only useful for importing other @Configuration files and is only useful (and afaik) and functional on @Configuration classes. When putting the @Import on a test class it will be no good as it won't be processed.

@Configuration
@Import(PersistenceConfig.class)
public class MainConfig {}

Using @Import can be useful if for instance you have disabled component scanning for @Configuration classes or you need an @Configuration class from a package not covered by your component-scan.

Note: There is also @ImportResource which does the same for older XML based configuration files.

The reverse is valid for @ContextConfiguration as that is only useful on Spring based test classes (tests ran with the SpringRunner for jUnit 4). It is used to supply the test with the configuration parameters to make up the test configuration. It can be a collection of XML, javaconfig (or a combination thereof).

@RunWith(SpringRunner.class)
@ContextConfiguration( classes = {MainConfig.class, TestConfig.class})
public MyTest {}

It also allows to specify what to use to load those configuration (amongst others).


in Spring Boot @Import(SomeConfiguration.class) adds configuration class to existing context. It is useful with test slices:

@DataJpaTest
@Import(SomeConfiguration.class)
class TestSomething(){...}

Here you have access to repositories and your beans from SomeConfiguration class.

@ContextConfiguration(classes = SomeConfiguration.class) mean use only this configuration , which could not work with eg. DataJpaTest.