Annotation @Import
The use of @Import
is when we want to import additional configuration.
Alternatively, we can use @ComponentScan
to automatically pick up all components including those who has @Configuration
Use case 1
One of the use case of @Import
is to use it when developing libraries. That's when you don't have access to @SpringBootApplication
For example:
Library A:
@Configuration
public class ConfigurationA {
@Bean
public ServiceA serviceA() {
return new ServiceA();
}
}
Library B:
@Configuration
@Import('ConfigurationA.class')
public class ConfigurationB {
@Bean
public ServiceA serviceB(ServiceA serviceA) {
return new ServiceB(serviceA);
}
}
Use case 2
You don't wanna use @SpringBootApplication
auto @ComponentScan
but manually specify which component to scan:
import org.springframework.boot.SpringApplication;
import org.springframework.boot.SpringBootConfiguration;
import org.springframework.context.annotation.Import;
@SpringBootConfiguration
@Import({ SomeConfiguration.class, AnotherConfiguration.class })
public class MyApplication {
public static void main(String[] args) {
SpringApplication.run(MyApplication.class, args);
}
}