Loading multiple Spring beans configuration files example

The loading multiple Spring beans configuration files example shows you how to import multiple spring xml configuration files. When you create a application with multiple layers. I strongly recommend you to configure each logical layer or module in a Spring XMl configuration file in your application. This configuration helps your source code more maintainable. Finally, You can use the ApplicationContext constructor to load bean definitions from an array of XML configuration filenames. Or you can also use the element to load bean definitions from other files.

Application Data Access Object(DAO) layer
We are structuring the application in multiple layers. First of all, We create the Data Access Object(DAO) layer with a simple class HelloDAO.

Now, We are going to configure this DAO layer as a spring bean in a Spring XML configuration file named dao-config.xml, like below:

Application Service layer

Next, we are creating Service layer with HelloService class. This class uses HelloDAO to say a message.

Now, We are going to configure this Service layer as a spring bean in a Spring XML configuration file named service-config.xml, like below:

Application Layer XML Configuration
We are creating a Application Layer XML Configuration file named spring-config.xml. This file will including two above XML Configuration files by using the element to import files dao-config.xml and service-config.xml. This file must be in the same directory or classpath location as the parent file doing the importing.

Demo Application
In this Loading multiple Spring beans configuration files example, we create main class and load all the bean definitions using the constructor of the ApplicationContext. The constructor arguments contain one Appication XML Configuration because we are using the element.

Run the above main, the output should display like below:

That’s all on the tutorial Loading multiple Spring beans configuration files example.

References
ClassPathXmlApplicationContext JavaDoc
Spring Reference Documentation

Download the complete source code, click link below

spring-multiple-bean-configuration-files.zip (17 downloads)

Leave a Comment

*

Please share it if you found this useful
Hide Buttons