Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How should you organize applicationContext files for a multi-module Spring Maven project?

I have a multi-module Maven project that uses Spring IoC, something like

parent-proj
  - module1
  - module2
  - module3
  - web-module

I question is:

What is the best practice to assemble applicationContext files? Should I create a gigantic applicationContext-web.xml in the web-module? Or should I create applicationContext-module<#>.xml in each sub-module, and import all of them in my applicationContext-web.xml?

I have been using the second option. Now it looks like things a bit out of control (e.g. beans override beans with the same id, etc).

Thanks.

like image 872
scabbage Avatar asked Oct 16 '12 18:10

scabbage


People also ask

What is multi-module project in Maven?

A multi-module project is built from an aggregator POM that manages a group of submodules. In most cases, the aggregator is located in the project's root directory and must have packaging of type pom. The submodules are regular Maven projects, and they can be built separately or through the aggregator POM.


2 Answers

First, if module1, module2 and module3 are purely java libraries (for instance, contains Domain Model, DAO, Service classes and etc) that are referenced and used in web-module, we usually don't manipulate Spring container in this purely java libraries.

Second, you should not split Spring container by project module. Depend on the demand, you can spilt Spring container by application layer and define multiple applicationContext files in web-module project (to avoid single gigantic applicationContext.xml). For instance, this is what we usually do:

web-module/src/main/webapp/WEB-INF:
  applicationContext-dataAccess.xml
  applicationContext-dataStore.xml
  applicationContext-security.xml
  applicationContext-web.xml
  ... ...
  web.xml

Hope that make sense.

like image 157
yorkw Avatar answered Sep 30 '22 10:09

yorkw


I prefer the second method too but using Spring classpath*: pseudo url. Something like:

<import resource="classpath*:META-INF/module-context.xml" />

This will load any module xml bean definition in my modules META-INF folder.

Now it looks like things a bit out of control (e.g. beans override beans with the same id, etc).

That is just a matter of organizing projects. I always try to use @Autowired so Spring can resolve dependencies based on the interfaces I declare. And of course, I never scan packages outside my modules to evade this kind of problems on Id's.

If autowiring is not possible, then declare beans only through xml and put them ids there.

The basic idea (not for spring but for modular projects) is well explained here.

like image 32
ElderMael Avatar answered Sep 30 '22 08:09

ElderMael