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 annotation in Spring allows you to load bean definitions from one or more another @Configuration files or Components. You might not want to configure all the beans in one configuration file.
@ContextConfiguration defines class-level metadata that is used to determine how to load and configure an ApplicationContext for integration tests.
Indicates that a class declares one or more @Bean methods and may be processed by the Spring container to generate bean definitions... @Configuration classes may be composed using the @Import annotation, not unlike the way that works in Spring XML.
An alternative way to import the bean is to use the SpringApplicationBuilder's sources method. Since we have already imported the bean, the line is commented. @Autowired private TimeService timeService; Now that the bean is registered, we can inject it into the field.
@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
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With