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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With