Spring - Using @Import

[Last Updated: Nov 26, 2020]

In a previous 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.


Bean classes

package com.logicbig.example;

class DataSourceBean {

  public String getData() {
      return "some app data";
package com.logicbig.example;

import org.springframework.beans.factory.annotation.Autowired;

public class Client {
  private DataSourceBean dataSourceBean;

  public void showData() {

Configuration classes

package com.logicbig.example;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

public class DataSourceConfig {
  DataSourceBean dataSourceBean() {
      return new DataSourceBean();

Following @Configuration class imports the above one.

package com.logicbig.example;

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);


some app data

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

Example Project

Dependencies and Technologies Used:

  • spring-context 4.3.4.RELEASE: Spring Context.
  • JDK 1.8
  • Maven 3.6.3

Spring - @Import Example Select All Download
  • spring-import-annotation-example
    • src
      • main
        • java
          • com
            • logicbig
              • example

    See Also