Thursday, 8 November 2018

Aggregating @Configuration classes with @Import | Spring Tutorial

🚀 Master Modular Spring JavaConfig!

Subscribe to Ram N Java for clean architectural patterns, Spring framework tutorials, and code walkthroughs!

🔔 Subscribe to Ram N Java

What Is the @Import Annotation in Spring?

In large-scale enterprise Java applications, keeping all bean definitions inside a single configuration class quickly leads to bloated, unmaintainable code. Spring's @Import annotation provides an elegant solution by allowing developers to split bean configurations across focused, modular @Configuration classes and aggregate them cleanly into a central configuration hub.

How Aggregating Configuration Works

Instead of registering multiple configuration classes manually when initializing the container, you designate one primary or root configuration class and aggregate other specialized classes:

  • Modular Configuration Classes: Separate your beans logically into domain-specific modules (such as AppConfigA and AppConfigB).
  • Aggregation Hub: Annotate a root configuration class with @Import({AppConfigA.class, AppConfigB.class}) to consolidate the configurations.
  • Simplified Container Bootstrapping: Pass only the main configuration class to AnnotationConfigApplicationContext. Spring automatically discovers and loads all imported classes and their associated @Bean definitions.

Step-by-Step Implementation Flow

  1. Define Feature Configs: Create individual configuration classes annotated with @Configuration, defining beans specific to their feature.
  2. Create Main Config: Define a main aggregation class (e.g., AppConfig) and apply @Import passing an array of module configuration classes.
  3. Initialize ApplicationContext: Instantiate the container with new AnnotationConfigApplicationContext(AppConfig.class).
  4. Access Beans: Retrieve beans declared across any of the imported configuration classes seamlessly from the single context.

Major Architectural Benefits

  • Separation of Concerns: Keeps configuration files cohesive, lightweight, and focused on specific domains (e.g., database, security, or business logic).
  • Easier Unit & Integration Testing: Allows test suites to bootstrap only relevant configuration modules rather than the entire application graph.
  • Clean Maintenance: Adding, removing, or swapping modular features becomes as simple as updating an entry in the @Import array.

Recommended Next Videos

Continue your deep dive into Spring configuration and annotations with these tutorials from our channel:


Click here to watch on Youtube:
https://www.youtube.com/watch?v=GRitnworI4c&list=UUhwKlOVR041tngjerWxVccw

Click the below Image to Enlarge:

Aggregating @Configuration classes with @Import | Spring Tutorial

Aggregating @Configuration classes with @Import | Spring Tutorial
pom.xml

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <groupId>com.ram.core</groupId>
    <artifactId>SpringDemo</artifactId>
    <packaging>jar</packaging>
    <version>1.0-SNAPSHOT</version>
    <name>SpringHelloWorld</name>
    <url>http://maven.apache.org</url>

    <properties>
        <spring.version>5.0.2.RELEASE</spring.version>
    </properties>

    <dependencies>
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>3.8.1</version>
            <scope>test</scope>
        </dependency>

        <!-- Spring 5 dependencies -->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-core</artifactId>
            <version>${spring.version}</version>
        </dependency>

        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-context</artifactId>
            <version>${spring.version}</version>
        </dependency>
    </dependencies>
</project>

Employee.java

package com.ram.core;

/**
 * Spring bean
 *
 */

public class Employee
{
    private String name;

    public Employee(String name)
    {
        System.out.println(this.getClass().getName()
                + ", Employee(String name) constructor is called, " + name);

        this.name = name;
    }


    public void employeeDetails()
    {
        System.out.println("Employee Name =  " + name);
    }
}

Customer.java

package com.ram.core;

/**
 * Spring bean
 *
 */

public class Customer
{
    private String name;

    public Customer(String name)
    {
        System.out.println(this.getClass().getName()
                + ", Customer(String name) constructor is called, " + name);

        this.name = name;
    }

    public void customerDetails()
    {
        System.out.println("Customer Name =  " + name);
    }
}

EmployeeConfig.java

package com.ram.config;

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

import com.ram.core.Employee;

@Configuration
public class EmployeeConfig
{

    @Bean(name = "employee")
    public Employee employee()
    {

        System.out.println(
                "In EmployeeConfig employee() is called by the Spring container");
        return new Employee("Peter");

    }
}

CustomerConfig.java

package com.ram.config;

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

import com.ram.core.Customer;

@Configuration
public class CustomerConfig
{

    @Bean(name = "customer")
    public Customer customer()
    {
        System.out.println(
                "In CustomerConfig employee() is called by the Spring container");
        return new Customer("John");
    }

}

AppConfig.java

package com.ram.config;

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

@Configuration
@Import({ EmployeeConfig.class, CustomerConfig.class })
public class AppConfig
{

}

App.java

package com.ram.core;

import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;

import com.ram.config.AppConfig;

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

        System.out.println("---------------------------------------");
     
        Employee employee = (Employee) context.getBean("employee");
        System.out.println("Got employee object from the ApplicationContext");
        employee.employeeDetails();
     
        System.out.println("---------------------------------------");
     
        Customer customer = (Customer) context.getBean("customer");
        System.out.println("Got customer object from the ApplicationContext");
        customer.customerDetails();

    }
}

Output

Oct 07, 2018 7:32:15 AM org.springframework.context.support.AbstractApplicationContext prepareRefresh
INFO: Refreshing org.springframework.context.annotation.AnnotationConfigApplicationContext@5f4da5c3: startup date [Sun Oct 07 07:32:15 IST 2018]; root of context hierarchy
In EmployeeConfig employee() is called by the Spring container
com.ram.core.Employee, Employee(String name) constructor is called, Peter
In CustomerConfig employee() is called by the Spring container
com.ram.core.Customer, Customer(String name) constructor is called, John
---------------------------------------
Got employee object from the ApplicationContext
Employee Name =  Peter
---------------------------------------
Got customer object from the ApplicationContext
Customer Name =  John

Click the below link to download the code:
https://sites.google.com/site/ramj2eev2/java_basics/SpringDemo_aggregate_import.zip?attredirects=0&d=1

Github Link:
https://github.com/ramram43210/javaee/tree/master/Spring_2018/SpringDemo_aggregate_import

Bitbucket Link:
https://bitbucket.org/ramram43210/spring/src/e16b8c6ef73a72464fa5812e24080179c4adc913/Spring_2018/SpringDemo_aggregate_import/?at=master

See also:

  • All JavaEE Videos Playlist
  • All JavaEE Videos
  • All JAVA EE Links
  • Spring Tutorial
  • Servlets Tutorial
  • All Design Patterns Links
  • JDBC Tutorial
  • Java Collection Framework Tutorial
  • JAVA Tutorial
  • Kids Tutorial
  • Cooking Tutorial
  • Tutorials