1

I've got the a WEB-INF/web.xml file with a couple of servlets, along with a context listener which I use to bootstrap the application. I'd like to use Spring in this web application. What's the best way to work Spring into this so I can use Spring's injection mechanisms throughout the entire application - even in the servlets which exists today?

<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.5" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">
    <display-name>Company's XMLRPC service</display-name>
    <!-- Servlet Listeners -->
    <listener>
        <listener-class>com.company.download.context.DefaultServletContextListener</listener-class>
    </listener>

    <!-- Servlet Declarations -->
    <servlet>
        <servlet-name>DefaultTrackDownloadServlet</servlet-name>
        <servlet-class>com.company.download.web.impl.DefaultTrackDownloadServlet</servlet-class>
    </servlet>
    <servlet>
        <servlet-name>DefaultXmlRpcServlet</servlet-name>
        <servlet-class>com.company.download.web.impl.DefaultXmlRpcServlet</servlet-class>
    </servlet>

    <!-- Servlet Configurations -->
    <servlet-mapping>
        <servlet-name>DefaultTrackDownloadServlet</servlet-name>
        <url-pattern>/track</url-pattern>
    </servlet-mapping>
    <servlet-mapping>
        <servlet-name>DefaultXmlRpcServlet</servlet-name>
        <url-pattern>/*</url-pattern>
    </servlet-mapping>
    <session-config>
        <session-timeout>
            30
        </session-timeout>
    </session-config>
</web-app>
sbrattla
  • 5,274
  • 3
  • 39
  • 63

1 Answers1

2

Can Spring “live” alongside other servlets in the same webapp?

Yes, Spring MVC is basically just a DispatcherServlet that can make use of a ContextLoaderListener.

These two classes are already setup to interact with one or more ApplicationContext instances and have Spring manage the declared beans.

Your custom Servlet classes are not. If you need to inject a bean into your own Servlet instances, you need to get a reference to the ApplicationContext from the ContextLoaderListener and get the beans you want. There are a few options, whether you do it yourself or use built-in features.

The ContextLoaderListener stores the ApplicationContext it loads into a ServletContext attribute named

org.springframework.web.context.WebApplicationContext.ROOT

So you can retrieve it with that (there's a constant for easy use)

ApplicationContext ac = (ApplicationContext) config.getServletContext().getAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE);

Other options exist, see some of them here:

Community
  • 1
  • 1
Sotirios Delimanolis
  • 274,122
  • 60
  • 696
  • 724