You're mixing up two concepts: Servlets and Spring's ApplicationContext
. Servlets are managed by your Servlet container, let's take Tomcat for example. The ApplicationContext
is managed by Spring.
When you declare a Servlet
in your deployment descriptor as
<servlet>
<servlet-name>servletOne</servlet-name>
<servlet-class>mypackage.servletOne</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>servletOne</servlet-name>
<url-pattern>/servletOne</url-pattern>
</servlet-mapping>
The Servlet container will create an instance of your mypackage.servletOne
class, register it, and use it to handle requests. This is what it does with the DispatcherServlet
which is the basis of Spring MVC.
Spring is an IoC container that uses ApplicationContext
to manage a number of beans. The ContextLoaderListener
loads the root ApplicationContext
(from whatever location you tell it to). The DispatcherServlet
uses that root context and must also load its own. The context must have the appropriate configuration for the DispatcherServlet
to work.
Declaring a bean in the Spring context, like
<bean id="servletFirst" class="mypackage.servletOne">
<property name="message" ref="classObject" />
</bean>
regardless of the fact that it is of the same type as the <servlet>
declared in web.xml, is completely unrelated. The bean above has nothing to do with the <servlet>
declaration in the web.xml.
As in my answer here, because the ContextLoaderListener
puts the ApplicationContext
it creates into the ServletContext
as an attribute, that ApplicationContext
is available to any Servlet container managed object. As such, you can override the HttpServlet#init(ServletConfig)
in your custom HttpServlet
classes, like so
@Override
public void init(ServletConfig config) throws ServletException {
super.init(config);
ApplicationContext ac = (ApplicationContext) config.getServletContext().getAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE);
this.someObject = (SomeBean)ac.getBean("someBeanRef");
}
assuming that your root ApplicationContext
contains a bean called someBeanRef
.
There are other alternatives to this. This, for example.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…