Home > Java > Modularity in Spring configuration

Modularity in Spring configuration

The following goes into more detail what I already ranted about in one of my previous post.

In legacy Spring applications I’ve to develop new features in, I regularly stumble upon a big hindrance that slows down my integration-testing effort. This hindrance, and I’ll go as far as naming it an anti-pattern, is to put every bean in the same configuration file (either in XML or in Java).

The right approach is to define at least the following beans in a dedicated configuration component:

  • Datasource(s)
  • Mail server
  • External web services
  • Every application dependency that doesn’t fall into one of the previous category

Depending on the particular context, we should provide alternate beans in test configuration fragments. Those alternatives can either be mocked beans or test doubles. In the first case, I would suggest using the Springockito framework, based upon Mockito; in the second case, tools depend on the specific resource: in-memory database (such as HSQLDB, Derby or H2*) for datasource and GreenMail for mail server.

It is up to the application and each test’s responsibility to assemble the different required configuration fragments to initialize the full-fledged Spring application context. Note that coupling fragments together is also not a good idea.

* My personal preference goes to H2 these days

Send to Kindle
Categories: Java Tags:
  1. June 5th, 2013 at 11:15 | #1

    I agree and I add a personal tip, which is giving me some satisfaction. By modularizing even the production beans.xml files (I mean, you don’t have a single file, but multiple ones: e.g. a core, and then those of self-contained extra modules) you can easily implement a “poor’s man” dynamic, modularized system. For instance, in a webapp of mine, the path given to Spring to find the beans.xml is something such as:


    The first part (classpath*:/META-INF/*AutoBeans.xml) is static, and I’m using a naming convention so that everything that must be automatically activated is configured in a file that ends with “AutoBeans.xml”. The remaining part is appended before boot by reading a property file. This means that the application can be configured in multiple “personalities”. Of course, this is not as safe as OSGi, as you don’t have true modules which dinamically check for dependency consistency, but in simple cases it works and doesn’t bring in the OSGi complexity.

  1. No trackbacks yet.