@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).
@ContextConfiguration
is only usable in tests in other code it doesn't do anything.@Import
is useless on a test and will only be useful on@Configuration
classes to import other configuration classes (with@ImportResource
you can import XML configuration files).@Import
- and this is it@Import
(aka include, load etc) other java configuration classes. For instance those not covered by component scanning (or maybe you disabled component scanning for@Configuration
files). Or to create a separate configuration for test which@Import
s the original configuration so that you can override beans ...@Import
on test class, why to use@ContextConfiguration
here? sorry if I'm being stupid:)@Import
is only useful (and functional) on@Configuration
classes. It won't do anything on a test class, the only thing it does is take up a line of code.