72 Miles

Recent News

Archives

Enjoy our content? Please subscribe to read new content weekly.   
June 5, 2008 @ 8:48 pm

Spring: Loading Multiple Contexts


I have already argued that many application contexts are better than a single application context. But how the heck do you load more than one context?

There are a couple of ways to do this.

web.xml

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, yo 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

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?

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.

Any benefits to going with the application context import method?

Now that you've read what we think, what did you like about the post? Where do you think we went wrong? Join or start the discussion.

Filed under Software Development, Spring

About the Author

Mike Nereson has been a professional software developer since 2000. He thinks open source is rad, and is an active volunteer Fire Fighter.

Leave a Comment

About

72 Miles Software - open source software, search engine optimization analytics, and software startup information. Software by design. Read More

Categories

Links

Sitemap