Spring: Many applicationContext.xml > One applicationContext.xml

This is a short introduction to splitting up your bean definitions from one single Spring application context, to many application contexts. That is, from one XML file to many XML files.

The general idea is to have one single primary application context, usually titled
applicationContext.xml, and then many other application contexts with are named what they contain.

Example

  • applicationContext.xml
  • applicationContext-dao.xml
  • applicationContext-dao-datasource.xml
  • applicationContext-ldap.xml
  • applicationContext-aspects.xml
  • applicationContext-web.xml

Breakdown

In this example, your DAO definitions, transaction managers, and DAO or integration interceptors are defined in applicationContext-dao.xml. We have further broken the DAO application context to a dao-datasource which contains our data sources. LDAP configuration, beans, and DAOs are in their own applicationContext-ldap.xml.

Benefits

Why so many? There have been a few benefits so far.

  • Clearly, working with a smaller XML file is easier than working with one enormous file. It is easier to maintain and easier to read.
  • Testing. When I wrote my tests for LDAP, I had my LDAP configuration in applicationContext.xml, but then every time I ran an LDAP test, I would get the WebApplicationContext, which would import applicationContext-hibernate, which would connect to the database, tests took forever, needless resources used… Anyway, now I just get applicationContext-ldap.xml which only contains LDAP configurations, so no needless resources are loaded.
  • Including. Finally, its really easy to comment out a line like
    <import resource="applicationContext-aspects.xml"/>

    and quickly have all my aspects, which for me only write logs, disabled.

Does anyone else use multiple application context files? See any other benefits? Or problems?