Spring - Using @Import

[Updated: Aug 9, 2016, Created: Feb 5, 2016]

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;

@Configuration
@Import(DataSourceConfig.class)
public class AppConfig {

    @Bean
    Client clientBean() {
        return new Client();
    }

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

@Configuration
class DataSourceConfig {

    @Bean
    DataSourceBean dataSourceBean() {
        return new DataSourceBean();
    }
}

class Client {
    @Autowired
    private DataSourceBean dataSourceBean;

    public void showData() {
        System.out.println(dataSourceBean.getData());
    }
}

class DataSourceBean {

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

Maven Dependency:

<dependency><groupid>org.springframework</groupid><artifactid>spring-context</artifactid><version>4.2.3.RELEASE</version></dependency>

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

See Also