Search This Blog

Friday, 23 November 2012

Importing from other configuration files

One of the best practises we follow in Application development is modularity. Separation of concern is an important design practise that can also be applied to our XML configuration.
If we were to write a Spring application and to define a whole collection of beans in a single XML file it would result in a very unmanageable and bulky file. Maintaining and understanding this file would be a near impossible task.
Spring provides us with techniques to define the beans in separate XML files.  So our data layer beans can go in one XML file, domain layer beans can go in another configuration file and on. In case of separate projects, the files will end up in jars and on the class path of the integration project.
I created a simple application that uses a combination of XML configuration files.
Complex project structure
As can be seen jar.xml is a Spring configuration file that is present on the class path:
<bean id="jarBean" class="com.jar.JarBean">
    <property name="name" value="jarBean" />
The JarBean class is a simple Bean
public class JarBean {
    private String name;
The other XML file is beans.xml :
<bean id="importedBean" class="com.test.Bean" >
    <property name="name" value="imported"/>
The bean defined here is another simpleton:
public class Bean {
    private String name;
//setter getter methods
Our top level XML file is the one from where which the execution begins. The application context is loaded from this file.
public class TestCode {
    public static void main(String[] args) {
        final ApplicationContext applicationContext = new ClassPathXmlApplicationContext(
        Bean topBean = (Bean) applicationContext.getBean("topBean");
        Bean importedBean = (Bean) applicationContext.getBean("importedBean");
        JarBean jarBean = (JarBean) applicationContext.getBean("jarBean");
The content of our top level configuration file is as below:
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns=""
    xsi:schemaLocation="" >

    <import resource="/imports/beans.xml"/>
    <import resource="classpath:jar.xml"/>
    <bean id="topBean" class="com.test.Bean" >
        <property name="name" value="direct"/>
In the XML file we load bean definitions from two other external files. The first file is loaded relative to the top-file.xml.This allows access to the bean with id "importedBean". The second file is present in the class path and is imported from the same. This gives access to bean with id "jarBean"


  1. Good explanation!. This is what I was exactly looking for. Thank you very much.

  2. If you need your ex-girlfriend or ex-boyfriend to come crawling back to you on their knees (even if they're dating somebody else now) you need to watch this video
    right away...

    (VIDEO) Text Your Ex Back?