Thursday, 8 November 2018

How to load multiple Spring bean configuration files | Spring Tutorial

Master Spring & Java Development!

Subscribe to Ram N Java for clean, beginner-friendly coding guides!

🔔 Subscribe to Ram N Java

Why Split Spring Configurations?

As enterprise applications grow, putting every bean definition into a single XML configuration file makes maintenance difficult and harms code readability. Splitting your configuration logically (such as separate files for databases, security, and business services) keeps your architecture modular and clean.

In this guide, you will learn how to easily load multiple bean configuration XML files into a single Spring ApplicationContext.

How to Load Multiple XML Files

Spring offers flexible ways to bootstrap an ApplicationContext with multiple configuration sources:

  • String Array Constructor: Pass an array of configuration filenames directly to ClassPathXmlApplicationContext(new String[] {"spring-beans1.xml", "spring-beans2.xml"}).
  • Using the <import> Tag: Create a master configuration file that aggregates individual XML files using the <import resource="..."/> element, loading only the root context file in Java code.

Key Benefits for Clean Architecture

  1. Modularity: Keep component definitions grouped logically by layer or feature.
  2. Team Collaboration: Multiple developers can work on distinct module configurations without merge conflicts.
  3. Easy Testing: Swap specific configuration files during unit and integration testing without touching production setups.

Recommended Next Videos from Ram N Java


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

Click the below Image to Enlarge:
How to load multiple Spring bean configuration files | Spring Tutorial |

How to load multiple Spring bean configuration files | 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>SpringHelloWorld</artifactId>
    <packaging>jar</packaging>
    <version>1.0-SNAPSHOT</version>
    <name>SpringDemo</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>

Customer.java

package com.ram.core;

/**
 * Spring bean
 *
 */

public class Customer
{
    private String name;

    public void setName(String name)
    {
        System.out.println(this.getClass().getName()
                + ", setName(String name) method is called " + name);
        this.name = name;
    }

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

Employee.java

package com.ram.core;

/**
 * Spring bean
 *
 */

public class Employee
{
    private String name;
   
    public void setName(String name)
    {
        System.out.println(this.getClass().getName()
                + ", setName(String name) method is called " + name);
        this.name = name;
    }

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

customer.xml

<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-4.3.xsd">


    <bean id="customer" class="com.ram.core.Customer">
        <property name="name" value="John David" />
    </bean>

</beans>

employee.xml

<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-4.3.xsd">


    <bean id="employee" class="com.ram.core.Employee">
        <property name="name" value="Peter" />
    </bean>

</beans>

SpringBeans.xml

<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-4.3.xsd">


    <import resource="config/customer.xml"/>
    <import resource="config/employee.xml"/>

</beans>


App.java

package com.ram.core;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class App
{
    public static void main(String[] args)
    {
        ApplicationContext context = new ClassPathXmlApplicationContext(
                "SpringBeans.xml");

        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 06, 2018 9:18:50 AM org.springframework.context.support.AbstractApplicationContext prepareRefresh
INFO: Refreshing org.springframework.context.support.ClassPathXmlApplicationContext@5a2e4553: startup date [Sat Oct 06 09:18:50 IST 2018]; root of context hierarchy
Oct 06, 2018 9:18:51 AM org.springframework.beans.factory.xml.XmlBeanDefinitionReader loadBeanDefinitions
INFO: Loading XML bean definitions from class path resource [SpringBeans.xml]
Oct 06, 2018 9:18:51 AM org.springframework.beans.factory.xml.XmlBeanDefinitionReader loadBeanDefinitions
INFO: Loading XML bean definitions from class path resource [config/customer.xml]
Oct 06, 2018 9:18:51 AM org.springframework.beans.factory.xml.XmlBeanDefinitionReader loadBeanDefinitions
INFO: Loading XML bean definitions from class path resource [config/employee.xml]
com.ram.core.Customer, setName(String name) method is called John David
com.ram.core.Employee, setName(String name) method is called Peter
---------------------------------------
Got employee object from the ApplicationContext
Employee Name =  Peter
---------------------------------------
Got customer object from the ApplicationContext
Customer Name =  John David

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

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

Bitbucket Link:
https://bitbucket.org/ramram43210/spring/src/e16b8c6ef73a72464fa5812e24080179c4adc913/Spring_2018/SpringDemo_Split_large_file/?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
  • No comments:

    Post a Comment

    Tutorials