Search code examples
javaspring-mvcweb.xml

Loading context in Spring using web.xml


Is there a way that a context can be loaded using web.xml in a Spring MVC application?


Solution

  • From the spring docs

    Spring can be easily integrated into any Java-based web framework. All you need to do is to declare the ContextLoaderListener in your web.xml and use a contextConfigLocation to set which context files to load.

    The <context-param>:

    <context-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>/WEB-INF/applicationContext*.xml</param-value>
    </context-param>
    
    <listener>
       <listener-class>
            org.springframework.web.context.ContextLoaderListener
       </listener-class>
    </listener> 
    

    You can then use the WebApplicationContext to get a handle on your beans.

    WebApplicationContext ctx = WebApplicationContextUtils.getRequiredWebApplicationContext(servlet.getServletContext());
    SomeBean someBean = (SomeBean) ctx.getBean("someBean");
    

    See http://static.springsource.org/spring/docs/2.5.x/api/org/springframework/web/context/support/WebApplicationContextUtils.html for more info