Spring - Using @Import

[Last Updated: Aug 28, 2018]

In the last tutorial we saw how to use multiple classes by providing all @Configuration classes to the constructor of AnnotationConfigApplicationContext. That approach may not always be 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 this kind of support. It is the equivalent to the <import/> element in a bean XML file.

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Import;

public class AppConfig {

    Client clientBean() {
        return new Client();

    public static void main(String[] args) {
        AnnotationConfigApplicationContext context =
              new AnnotationConfigApplicationContext(AppConfig.class);

class DataSourceConfig {

    DataSourceBean dataSourceBean() {
        return new DataSourceBean();

class Client {
    private DataSourceBean dataSourceBean;

    public void showData() {

class DataSourceBean {

    public String getData() {
        return "some data";

Maven Dependency:


Multiple configurations may be imported by supplying an array of classes to the @Import annotation.

See Also