Close

Spring - Using Multiple @Configuration Classes

[Last Updated: Nov 26, 2020]

To separate the concerns or to achieve modularization, we can define multiple @Configuration classes. During container initialization, we can use one of the following constructors of AnnotationConfigApplicationContext

public AnnotationConfigApplicationContext(Class<?>... annotatedConfigurationClasses)
public AnnotationConfigApplicationContext(String... basePackages)

Example

Beans

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();
  }
}
package com.logicbig.example;

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

@Configuration
public class AppConfig {

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

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

Output

some app data

Example Project

Dependencies and Technologies Used:

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

Spring - Using multiple Configurations Select All Download
  • spring-multiple-configurations
    • src
      • main
        • java
          • com
            • logicbig
              • example
                • AppConfig.java

    See Also