Last Updated on 20 June 2019   |   Print Email
This Spring tutorial guides you how to configure Spring to use multiple XML beans configuration files.For large and complex Spring-based applications, it’s very common to break Spring’s application context file into multiple files in order to modularize the application’s configuration (beans definitions) into smaller pieces for easy maintenance. Spring allows this by providing the <import> element. Here’s a quick example:
This Spring’s application context configuration file includes three resources: daoBeans.xml, businessBeans.xml and servicesBeans.xml with each must be a complete, fully valid XML Spring’s beans definition file (including the root element <beans> and its xmlns attributes). Following are example code of each imported file above:daoBeans.xml:
Spring container will load all the imported files and merge them to produce a final application configuration, so beans in one file can refer to other beans declared in other files. For example, in the above example, the myServiceBean (declared in servicesBeans.xml file) refers to the myBusinessBean which is declared in the businessBeans.xml file, and the myBusinessBean refers to the bean myDaoBean which is declared in the daoBeans.xml file. The imported files are considered to be relative to the parent file. The following screenshot shows how these XML files are place in an Eclipse project:
Of course the imported file can import another file also, as shown in the following modified version of servicesBeans.xml file:
And the Spring container will throw a BeanDefinitionStoreException if it could not find a specified imported file.You can download a sample Spring MVC application (in Eclipse project) that demonstrates using multiple beans configuration files, in the attachments section below.
Nam Ha Minh is certified Java programmer (SCJP and SCWCD). He began programming with Java back in the days of Java 1.4 and has been passionate about it ever since. You can connect with him on Facebook and watch his Java videos on YouTube.
just by defining the beans in the .xml config files we do not load them into the spring IOC container correct? How do we actually register the beans? can these .xml files be auto scanned if we use @SpringBootApplication? or do we also have to import the parent file into some @Configuration file? i think those are registered by component scanning
Comments