Spring by Example Custom ServletContext Scope Module

David Winterfeldt

2008


The Spring by Example Custom ServletContext Scope module is a custom scope implementation for providing ServletContext (web application) scoped beans.

It can be useful for sharing a Spring bean between web applications if your servlet container has cross context support. Tomcat has cross context support that can be turned on by setting crossContext="true" on the Context. See Tomcat's context documentation for more details.

[Note]Note

Even though a bean can be shared between web contexts, only classes loaded by a parent classloader can be shared. The easiest thing to do is either share data as XML or in a Map or String (something JVM's core). Then there won't be any ClassCastExceptions. Or the server can be configured to have the shared class in the parent classloader. For example, in Tomcat the jar with the shared class could be put in Tomcat's lib directory, but this should be avoided as much as possible since it will cause your web applications to be tightly coupled together.

1. Spring Configuration

The custom ServletContextScope is registered with the CustomScopeConfigurer under the key 'servletContext'. The key can be used to specify the scope on a bean just like the default scopes 'singleton' or 'prototype'.

                
<bean class="org.springframework.beans.factory.config.CustomScopeConfigurer">
    <property name="scopes">
        <map>
            <entry key="servletContext">
                <bean class="org.springbyexample.web.context.ServletContextScope" />
            </entry>
        </map>
    </property>
</bean>
                
            

This is the same, but it specifies a specific context to use for storing and retrieving values.

                
<bean class="org.springframework.beans.factory.config.CustomScopeConfigurer">
    <property name="scopes">
        <map>
            <entry key="servletContext">
                <bean class="org.springbyexample.web.context.ServletContextScope" />
                    <property name="context" value="/advanced-form" />
                </bean>
            </entry>
        </map>
    </property>
</bean>