Tuesday, July 1, 2014

Load multiple contexts into spring

How do you load more than one context?

There are a couple of ways to do this.

web.xml contextConfigLocation

Your first option is to load them all into your Web application context via the ContextConfigLocation element. You’re already going to have your primary applicationContext here, assuming you’re writing a web application. All you need to do is put some white space between the declaration of the next context.

<context-param>
    <param-name>
                     contextConfigLocation
    </param-name>
    <param-value>
                    applicationContext1.xml
                    applicationContext2.xml
    </param-value>
</context-param>

<listener>
    <listener-class>
        org.springframework.web.context.ContextLoaderListener
    </listener-class>
</listener>


The above uses carriage returns. Alternatively, you could just put in a space.


<context-param>
    <param-name>
        contextConfigLocation
    </param-name>
    <param-value>
        applicationContext1.xml applicationContext2.xml
    </param-value>
</context-param>

<listener>
    <listener-class>
        org.springframework.web.context.ContextLoaderListener
    </listener-class>
</listener>

applicationContext.xml     import resource

Your other option is to just add your primary applicationContext.xml to the web.xml and then use import statements in that primary context.
In applicationContext.xml you might have…


<!-- hibernate configuration and mappings -->
<import resource="applicationContext-hibernate.xml"/>

<!-- ldap -->
<import resource="applicationContext-ldap.xml"/>

<!-- aspects -->
<import resource="applicationContext-aspects.xml"/>


Which strategy should you use?

I always prefer to load up via web.xml This allows me to keep all contexts isolated from each other. With tests, we can load just the contexts that we need to run those tests. This makes development more modular too as components stay loosely coupled, so that in the future I can extract a package or vertical layer and move it to its own module.
If you are loading contexts into a non-web application, I would use the import resource.
Any benefits to going with the application context import method over the web.xml contextConfigLocation?

No comments:

Post a Comment