You are mixing two concepts: servlets and Spring ApplicationContext . Servlets are managed by your Servlet container, for example, take Tomcat. ApplicationContext managed by Spring.
When you declare a Servlet in the 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 instantiate your class mypackage.servletOne , register it, and use it to process requests. This is what it does with the DispatcherServlet , which is the foundation of Spring MVC.
Spring is an IoC container that uses ApplicationContext to control the number of beans. ContextLoaderListener loads the ApplicationContext root (from anywhere you speak of). DispatcherServlet uses this root context and must also load its own. The context must have the appropriate configuration for the DispatcherServlet to work.
A bean declaration in a Spring context, for example
<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, it is not completely connected. The bean above has nothing to do with the <servlet> declaration in web.xml.
As in my answer here , since the ContextLoaderListener places the ApplicationContext , which it creates in ServletContext as an attribute, the ApplicationContext is available on any managed servlet container object. This way you can override HttpServlet#init(ServletConfig) in your custom HttpServlet classes, e.g.
@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 your root ApplicationContext contains a bean called someBeanRef .
There are other alternatives to this. This, for example.