/ 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

Nicolas Fränkel is a technologist focusing on cloud-native technologies, DevOps, CI/CD pipelines, and system observability. His focus revolves around creating technical content, delivering talks, and engaging with developer communities to promote the adoption of modern software practices. With a strong background in software, he has worked extensively with the JVM, applying his expertise across various industries. In addition to his technical work, he is the author of several books and regularly shares insights through his blog and open-source contributions.

Read More
Modularity in Spring configuration
Share this