Close

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.



Example

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 {
  @Autowired
  private DataSourceBean dataSourceBean;

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

Configuration classes

package com.logicbig.example;


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

@Configuration
public class DataSourceConfig {
  @Bean
  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;

@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();
  }
}

Output

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
                • AppConfig.java

    See Also