Is there any difference in usage of the annotations? Both the annotations allow to use multiple @Configuration
classes to create an ApplicationContext
. From their docs @ContextConfiguration
seems to be more suitable for test configuration and comes from an artifact for tests (spring-test
), however, I haven't found the actual difference.
Thank you for any thoughts!
@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( {MainConfig.class, TestConfig.class})
public MyTest {}
It also allows to specify what to use to load those configuration (amongst others).