What is the use case of @Import annotation?

If component scanning is enabled, you can split bean definitions in multi @Configuration classes without using @Import. And you don't need to provide all of them to the application context constructor.

I think the main purpose for @Import is to provide you a way to simplify multiple configurations registration if you'd like to avoid component scanning (as of Spring Framework 4.2, per reference manual).

There's a note in Spring Reference Documentation about @Import usage:

As of Spring Framework 4.2, @Import also supports references to regular component classes, analogous to the AnnotationConfigApplicationContext.register method. This is particularly useful if you’d like to avoid component scanning, using a few configuration classes as entry points for explicitly defining all your components.


Thus far, we've seen how to break up bean definitions into multiple @Configuration classes and how to reference those beans across @Configuration boundaries. These scenarios have required providing all @Configuration classes to the constructor of a JavaConfigApplicationContext, and this is not always ideal. Often it is preferable to use an aggregation approach, where one @Configuration class logically imports the bean definitions defined by another.

The @Import annotation provides just this kind of support, and it is the direct equivalent of the <import/> element found in Spring beans XML files.

http://docs.spring.io/spring-javaconfig/docs/1.0.0.M4/reference/html/ch04s03.html


I found a use of using the @Import annotation. I don't think it's the use case. If you are developing a set of libraries using Spring, probably you don't have a SpringBootApplication. So, you have not enabled any auto-scan to resolve beans.

If a bean declared in a configuration file in the library library-a is referred through dependency injection in library-b you need to use @Import to tell Spring how to resolve the bean.

As we said, in library-a you have this configuration file.

@Configuration
public class ConfigurationA {
    @Bean
    public BeanA beanA() {
       return new BeanA();
    }
}

In library-b you must have this configuration file if you want to use BeanA

@Configuration
@Import(ConfigurationA.class)
public class ConfigurationB {
    @Bean
    public BeanB beanB(BeanA beanA) {
       return new BeanB(beanA);
    }
}

Hope it helps.


With component scanning enabled it's difficult to immediately see where @Import adds value if your view of the world is limited to your own application and its packages. Where it can help is if you are importing bean libraries with their own package structure that you don't want to component scan.

You can place such libraries on your classpath and use @Import to cherry-pick @Configuration classes from within them. That's why it's often referred to as composition because you are composing your @Configuration class from multiple sources.