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.
For example, a single web project might contain the following contexts.
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.
Why so many? There have been a few benefits so far.
The Single Responsibility Principal is widely accepted and states that
… every object should have a single responsibility, and that all its services should be narrowly aligned with that responsibility.states that every object should have a single responsibility, and that all its services should be narrowly aligned with that responsibility.
The same holds true for XML contexts. The general ides is to make our contexts more robust and to be able to isolate a context’s tasks and capabilities. And clearly, working with a smaller XML file is easier than working with one enormous file. It is easier to maintain and easier to read.
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 and needless resources were used. Now I just get applicationContext-ldap.xml which only contains LDAP configurations, so no needless resources are loaded and tests remain quick.
Inclusion and Exclusion
Finally, its really easy to comment out a line like
and quickly have all my aspects, which for me only write logs, disabled. Or easy to add a line like
which overrides all of your DAO implementations with mock DAOs. This would be for testing.
Does anyone else use multiple application context files? See any other benefits? Or problems?