/ SPRING

Modularity in Spring configuration

Spring icon

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

Nicolas Fränkel

Nicolas Fränkel

Developer Advocate with 15+ years experience consulting for many different customers, in a wide range of contexts (such as telecoms, banking, insurances, large retail and public sector). Usually working on Java/Java EE and Spring technologies, but with focused interests like Rich Internet Applications, Testing, CI/CD and DevOps. Also double as a trainer and triples as a book author.

Read More
Modularity in Spring configuration
Share this